shared

package
v1.261122.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 57 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultAppStoreVersionSourceEditable = "editable"
	DefaultAppStoreVersionSourceLive     = "live"
)

Default App Store version resolution picks the version a caller most likely means when --version is omitted: the newest editable version, else the newest live version. This mirrors the fallback used by EAS metadata:pull.

View Source
const (
	LocalizationTypeVersion = "version"
	LocalizationTypeAppInfo = "app-info"
)
View Source
const (
	NextFlagUsage     = "Fetch next page using a links.next URL"
	PaginateFlagUsage = "Automatically fetch all pages (aggregate results)"
)

NextFlagUsage and PaginateFlagUsage are the --next and --paginate help lines of list commands; LimitFlagUsage gives their --limit help line.

View Source
const (
	// IOSProvisioningProfileExtension is the conventional extension for iOS,
	// tvOS, and other non-macOS provisioning profiles.
	IOSProvisioningProfileExtension = ".mobileprovision"
	// MacOSProvisioningProfileExtension is the conventional extension for
	// provisioning profiles used by macOS applications.
	MacOSProvisioningProfileExtension = ".provisionprofile"
)
View Source
const (
	// IncludeSensitiveFlagName is the per-invocation opt-in for printing secrets.
	IncludeSensitiveFlagName = "include-sensitive"

	// IncludeSensitiveFlagUsage documents the opt-in. It has no environment
	// variable default: a secret must never become visible because of ambient
	// configuration.
	IncludeSensitiveFlagUsage = "Print secret values such as demo account passwords instead of \"" +
		"(redacted)\"; applies only to this invocation"

	// IncludeSensitiveWarning is written to stderr whenever the opt-in is used.
	IncludeSensitiveWarning = "Warning: --include-sensitive prints secrets in plain text; " +
		"they can persist in shell history, CI logs, and terminal scrollback."
)
View Source
const (
	PrivateKeyEnvVar       = privateKeyEnvVar
	PrivateKeyBase64EnvVar = privateKeyBase64EnvVar
)
View Source
const (
	SubmitReadinessCreateModePlanned = "planned"
	SubmitReadinessCreateModeApplied = "applied"
)
View Source
const AmbiguousCandidateLimit = 10

AmbiguousCandidateLimit bounds how many candidates an ambiguity error lists. Remaining candidates are summarized as "... and N more".

View Source
const AmbiguousDiagnosticTextLimit = 256

AmbiguousDiagnosticTextLimit bounds each provider-supplied text field in a terminal ambiguity diagnostic. The limit is measured in bytes, with the truncation boundary adjusted to preserve valid UTF-8.

View Source
const FlagTerminatorSentinel = "\x00asc-flag-terminator"

FlagTerminatorSentinel preserves a leading `--` for commands that need to distinguish escaped positional tokens after flag.FlagSet removes the terminator. NUL cannot appear in a real process argument, so it cannot collide with operator input.

View Source
const (

	// MaxIndirectFileValueSize bounds a flag value read through @file:PATH.
	// Flag values are release notes, JSON bodies, or secrets, never bulk
	// artifacts, so a bounded read keeps a mistaken path from loading a
	// large file into memory.
	MaxIndirectFileValueSize = 1 << 20
)
View Source
const PKCS12EncodingFlagUsage = "PKCS#12 encoding: modern (AES-256-CBC, HMAC-SHA-256) or legacy (3DES, SHA-1 MAC) for importers that reject modern files"

PKCS12EncodingFlagUsage is the help text for --p12-encoding.

View Source
const PublishDefaultPollInterval = 30 * time.Second

PublishDefaultPollInterval is the default polling interval for build discovery.

View Source
const (
	ReportFormatJUnit = "junit"
)

CI report format types

View Source
const RootProfileFlagName = "profile"

RootProfileFlagName is the credential-profile selector bound by BindRootFlags. Only the root flag set binds it, but it is accepted before or after the command name, so surfaces that enumerate a command's accepted flags offer it alongside the command's own flags.

Variables

View Source
var AgeRatingDeclarationSparseFields = []string{
	"advertising", "alcoholTobaccoOrDrugUseOrReferences", "contests", "gambling", "gamblingSimulated",
	"gunsOrOtherWeapons", "healthOrWellnessTopics", "kidsAgeBand", "lootBox",
	"medicalOrTreatmentInformation", "messagingAndChat", "parentalControls", "profanityOrCrudeHumor",
	"ageAssurance", "sexualContentGraphicAndNudity", "sexualContentOrNudity", "socialMedia",
	"socialMediaAgeRestricted", "horrorOrFearThemes", "matureOrSuggestiveThemes", "unrestrictedWebAccess",
	"userGeneratedContent", "violenceCartoonOrFantasy", "violenceRealisticProlongedGraphicOrSadistic",
	"violenceRealistic", "ageRatingOverride", "ageRatingOverrideV2", "koreaAgeRatingOverride",
	"gracRatingClassificationNumber", "developerAgeRatingInfoUrl",
}

AgeRatingDeclarationSparseFields is the fields[ageRatingDeclarations] enum, which every operation that accepts the parameter shares.

View Source
var AppInAppPurchaseSparseFields = []string{
	"referenceName", "productId", "inAppPurchaseType", "state", "apps", "name", "reviewNote",
	"familySharable", "contentHosting", "inAppPurchaseLocalizations", "pricePoints", "content",
	"appStoreReviewScreenshot", "promotedPurchase", "iapPriceSchedule", "inAppPurchaseAvailability",
	"images", "offerCodes", "versions",
}

AppInAppPurchaseSparseFields is the fields[inAppPurchases] enum for operations that include IAPs from an app: GET /v1/apps, /v1/apps/{id}, and /v1/ciProducts/{id}/app. Other operations use narrower enums.

View Source
var AppInfoSparseFields = []string{
	"appStoreState", "state", "appStoreAgeRating", "australiaAgeRating", "brazilAgeRating",
	"brazilAgeRatingV2", "franceAgeRating", "koreaAgeRating", "app", "ageRatingDeclaration",
	"appInfoLocalizations", "primaryCategory", "primarySubcategoryOne", "primarySubcategoryTwo",
	"secondaryCategory", "secondarySubcategoryOne", "secondarySubcategoryTwo", "territoryAgeRatings",
	"kidsAgeBand",
}

AppInfoSparseFields is the fields[appInfos] enum, which every operation that accepts the parameter shares. kidsAgeBand stays last: API 4.5 removed it, but it remains accepted as a deprecated selector.

View Source
var ErrBundleIDNotFound = errors.New("bundle ID not found")

ErrBundleIDNotFound reports that no bundle ID has the requested identifier.

View Source
var ErrMissingAuth = errors.New("missing authentication")
View Source
var ErrMissingWebSession = errors.New("missing Apple web session")

ErrMissingWebSession reports that an `asc web` command needs a signed-in Apple web session that is not cached and cannot be created without a terminal. It keeps the usage exit code that this failure has always had, but it is not reported by the command and does not wrap flag.ErrHelp: the root renderer prints its message and hint instead of the command's usage page.

View Source
var ErrPending = errors.New("still pending")

ErrPending marks a bounded wait that stopped before its target reached a terminal state, after the command reported the pending state itself. Commands return it only when the caller opted in to a pending outcome, and it maps to the dedicated pending exit code instead of a failure.

View Source
var ErrUploadDeadline = errors.New("upload deadline reached")

ErrUploadDeadline marks an error caused by the deadline that ASC_UPLOAD_TIMEOUT controls, so the error hint names that setting even when the message itself does not mention an upload.

View Source
var RetentionMessageSparseFields = IncludedResourceFields("retentionMessages")

RetentionMessageSparseFields is the fields[retentionMessages] enum.

View Source
var SubscriptionGroupSparseFields = []string{
	"referenceName", "subscriptions", "subscriptionGroupLocalizations", "versions",
}

SubscriptionGroupSparseFields is the fields[subscriptionGroups] enum, which every operation that accepts the parameter shares.

Functions

func AltoolPrivateKeyPath

func AltoolPrivateKeyPath(creds ResolvedAuthCredentials) (string, error)

AltoolPrivateKeyPath returns a .p8 path for altool's --p8-file-path, writing PEM material loaded from the keychain or environment to a private temp file. It returns "" when creds carry no usable key.

func AmbiguousAppInfoError

func AmbiguousAppInfoError(appID, flag string, appInfos []asc.AppInfoCandidate) error

AmbiguousAppInfoError reports that an app has several app infos and names the flag that accepts one app info ID.

func AmbiguousAppStoreVersionError

func AmbiguousAppStoreVersionError(version, platform string, versions []asc.Resource[asc.AppStoreVersionAttributes], platformFlag, versionIDFlag string) error

AmbiguousAppStoreVersionError reports several App Store versions for one version string. When the matches span platforms and platformFlag is set, the candidates are the platform values to pass; otherwise the candidates are the version IDs for versionIDFlag (which may be empty when the command accepts no version ID).

func AmbiguousError

func AmbiguousError(kind, flag, selector string, candidates []AmbiguousCandidate) error

AmbiguousError builds an AmbiguousSelectionError for a selector value that matched several resources of kind; selector is quoted in the message.

func AmbiguousLocalizationError

func AmbiguousLocalizationError(kind, locale string, candidates []AmbiguousCandidate) error

AmbiguousLocalizationError reports duplicate localizations for one locale. App Store Connect should never return more than one, so no flag can select between them; the candidates are listed so the duplicate can be repaired.

func AppFieldsList

func AppFieldsList(exclude ...string) []string

AppFieldsList returns the fields[apps] enum, which every App Store Connect operation in docs/openapi/latest.json shares, without the values in exclude. The spec also lists appEncryptionDeclarations, but Apple production rejects it on every endpoint (400 "is not a valid field name" or HTTP 500, Nov 2026).

func AppUpdateRequiresWhatsNew added in v1.260407.0

func AppUpdateRequiresWhatsNew(ctx context.Context, client *asc.Client, appID, platform string) (bool, error)

AppUpdateRequiresWhatsNew returns true when the target app/platform has a previously released App Store version, which means whatsNew is required on every localization for update submissions. A released version is one that is live under either state spelling, or one that was removed from sale (a legacy appStoreState-only condition).

func ApplePayCertificateTypeList

func ApplePayCertificateTypeList() []string

ApplePayCertificateTypeList returns the certificate types that require a merchantId relationship.

func ApplyAppInfoLocalizationUpsert added in v1.260816.0

func ApplyAppInfoLocalizationUpsert(
	ctx context.Context,
	client *asc.Client,
	plan *AppInfoLocalizationUpsertPlan,
) (*asc.AppInfoLocalizationResponse, string, error)

ApplyAppInfoLocalizationUpsert performs a previously planned localization write.

func ApplyRootLoggingOverrides

func ApplyRootLoggingOverrides()

ApplyRootLoggingOverrides applies root-level logging flag overrides (--retry-log, --debug, --api-debug) into the shared ASC runtime.

func BindBuildFlagAlias

func BindBuildFlagAlias(fs *flag.FlagSet)

BindBuildFlagAlias accepts --build on a command that selects a build by --build-id or --build-number, both already bound on fs. App Store Connect build IDs are UUIDs and a build number (CFBundleVersion) is a list of at most three period-separated integers, so the value's shape says which one it is: a UUID or a URL (a build's self-link) is the build ID, any other value the build number.

func BindCIFlags

func BindCIFlags(fs *flag.FlagSet)

BindCIFlags registers CI-related flags for report output. These are separate from BindRootFlags to keep CI concerns isolated.

func BindFlagAlias

func BindFlagAlias(fs *flag.FlagSet, alias, canonical string)

BindFlagAlias accepts --alias as a second spelling of the flag canonical, which must already be bound on fs. The alias is hidden from help, and the root rewrites it to the canonical spelling before parsing, so it is validated, reported and sent exactly as the canonical flag is.

func BindIfExistsFlag

func BindIfExistsFlag(fs *flag.FlagSet, supported ...IfExistsMode) *string

BindIfExistsFlag registers --if-exists with the supported modes listed in the usage text. fail is always supported and is the default.

func BindIncludeSensitiveFlag added in v1.260731.0

func BindIncludeSensitiveFlag(fs *flag.FlagSet) *bool

BindIncludeSensitiveFlag registers --include-sensitive on the flag set.

func BindPrettyJSONFlag

func BindPrettyJSONFlag(fs *flag.FlagSet) *bool

BindPrettyJSONFlag registers a --pretty flag for JSON rendering.

func BindResourceIDFlag

func BindResourceIDFlag(fs *flag.FlagSet, name, resourceType, usage string) *string

BindResourceIDFlag registers a string flag that accepts a bare App Store Connect resource ID or the resource's API self-link. Self-links of another resource type, on another host, or with a longer path are rejected during flag parsing so the command exits with usage code 2 before any request.

func BindRootFlags

func BindRootFlags(fs *flag.FlagSet)

BindRootFlags registers root-level flags that affect shared CLI behavior.

func BuildAppKeywordsResponse

func BuildAppKeywordsResponse(keywords []string) *asc.AppKeywordsResponse

BuildAppKeywordsResponse converts a keyword list into the standard appKeywords response shape used by multiple keyword mutation commands.

func BuildConfirmDeleteCommand

func BuildConfirmDeleteCommand(config ConfirmDeleteCommandConfig) *ffcli.Command

BuildConfirmDeleteCommand builds a standard delete command requiring --id and --confirm and printing a caller-provided result payload.

func BuildCreateCommand

func BuildCreateCommand(config WriteCommandConfig) *ffcli.Command

BuildCreateCommand builds a create command that checks the ID flag and the required fields, sends one request and prints its response.

func BuildIDGetCommand

func BuildIDGetCommand(config IDGetCommandConfig) *ffcli.Command

BuildIDGetCommand builds a standard "get by ID" command.

func BuildPaginatedListCommand

func BuildPaginatedListCommand(config PaginatedListCommandConfig) *ffcli.Command

BuildPaginatedListCommand builds a list command that supports --next and --paginate semantics shared by many resources.

func BuildPricePointEqualizationsCommand added in v1.260407.0

func BuildPricePointEqualizationsCommand(config PricePointEqualizationsCommandConfig) *ffcli.Command

BuildPricePointEqualizationsCommand builds a standard equalizations list command with shared help/examples and --limit/--next/--paginate semantics.

func BuildUpdateCommand

func BuildUpdateCommand(config WriteCommandConfig) *ffcli.Command

BuildUpdateCommand builds an update command like BuildCreateCommand that also requires at least one of its fields.

func BuildUploadFailureError

func BuildUploadFailureError(upload *asc.BuildUploadResponse) error

BuildUploadFailureError describes a FAILED build upload with Apple's error details and recovery guidance. It returns nil for any other upload state.

func BuildsWaitHint

func BuildsWaitHint(appID, version, buildNumber, platform string) string

BuildsWaitHint names the builds wait command with the caller's selectors, for a build that was just uploaded and is not visible yet. An empty buildNumber selects the latest build.

func BundleIDPlatformList added in v1.260807.0

func BundleIDPlatformList() []string

BundleIDPlatformList returns the allowed BundleIdPlatform values.

func CanonicalCertificateType added in v1.260904.0

func CanonicalCertificateType(value string) (string, bool)

CanonicalCertificateType normalizes value and returns the matching App Store Connect certificate type. Callers must use the returned value rather than the raw flag input: App Store Connect matches the enum exactly, so a normalized spelling such as "ios-distribution" has to reach the API as "IOS_DISTRIBUTION".

func CanonicalizeAppStoreLocalizationLocale added in v1.260407.0

func CanonicalizeAppStoreLocalizationLocale(value string) (string, error)

CanonicalizeAppStoreLocalizationLocale canonicalizes known locale codes, rejects shorthand roots when the catalog only supports region/script-specific variants, and preserves unknown well-formed locale codes for forward compatibility.

func CertificateCreateTypeList added in v1.260904.0

func CertificateCreateTypeList() []string

CertificateCreateTypeList returns the certificate types asc certificates create can create. Use it for create help text and diagnostics so both discovery paths agree with what the command accepts.

func ClassifyLocalFileError

func ClassifyLocalFileError(err error, parameter string, contentCode DiagnosticCode) error

ClassifyLocalFileError applies LocalFileDiagnostic to a failure involving the local file named by parameter. A classified failure becomes an expected-negative validation error with its message and exit code unchanged; any other error is returned as is.

func CleanupTempPrivateKeys

func CleanupTempPrivateKeys()

CleanupTempPrivateKeys removes any temporary private key files created during this run.

func CollectPricePointsByTerritoryWith

func CollectPricePointsByTerritoryWith[A any](
	ctx context.Context,
	d *Deps,
	territories []string,
	fetch func(ctx context.Context, next string) (*asc.Response[A], error),
	customerPrice func(A) string,
) (map[string][]PriceLadderCandidate, error)

CollectPricePointsByTerritoryWith reads every page of a price-point collection requested with include=territory and groups the points by territory. When territories is set, a point from any other territory fails the read. Each page read's deadline comes from d.Timeout and the waits between attempts run on d.After.

func CommitBuildUploadFile added in v1.260404.0

func CommitBuildUploadFile(ctx context.Context, client *asc.Client, uploadID, fileID string, checksums *asc.Checksums) (*asc.BuildUploadFileResponse, error)

CommitBuildUploadFile marks a reserved upload file as uploaded and optionally persists source-file checksums. When the mutation result is ambiguous, it reads the parent build upload once and accepts success only when App Store Connect reports that processing has started or completed. A reconciled success returns a nil response because no authoritative file payload exists.

func CompareRFC3339DateStrings added in v1.260331.0

func CompareRFC3339DateStrings(current, best string) int

CompareRFC3339DateStrings compares two RFC3339 timestamps, falling back to trimmed string comparison when parsing fails.

func ContextWithResolvedTimeout

func ContextWithResolvedTimeout(ctx context.Context, defaultTimeout time.Duration) (context.Context, context.CancelFunc)

ContextWithResolvedTimeout returns a context with ASC timeout resolution and a package-provided default fallback duration.

func ContextWithTimeout

func ContextWithTimeout(ctx context.Context) (context.Context, context.CancelFunc)

func ContextWithTimeoutDuration

func ContextWithTimeoutDuration(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

ContextWithTimeoutDuration creates a context with a specific timeout.

func ContextWithUploadTimeout

func ContextWithUploadTimeout(ctx context.Context) (context.Context, context.CancelFunc)

func ContextWithUsageMessageRewrites added in v1.260904.0

func ContextWithUsageMessageRewrites(ctx context.Context, rewrites ...UsageMessageRewrite) context.Context

ContextWithUsageMessageRewrites returns a context carrying rewrites in addition to any already present.

Wrappers install their rewrites while a command is being entered, outermost first, whereas an error is rewritten on the way out, innermost first. The most recently installed rewrites are therefore applied first, which keeps a nested tree rendering exactly what the post-hoc error rewriters render.

func ContextWithoutTimeout

func ContextWithoutTimeout(ctx context.Context) context.Context

func CopyVersionMetadataFromSource

func CopyVersionMetadataFromSource(
	ctx context.Context,
	client *asc.Client,
	opts VersionMetadataCopyOptions,
) (*asc.AppStoreVersionMetadataCopySummary, error)

CopyVersionMetadataFromSource copies selected localization metadata from one version into another.

func DefaultUsageFunc

func DefaultUsageFunc(c *ffcli.Command) string

DefaultUsageFunc returns a usage string with bold section headers

func DescribeRelationshipLookupFailure

func DescribeRelationshipLookupFailure(err error, relationshipType string, parent RelationshipParent) error

DescribeRelationshipLookupFailure names the resource App Store Connect could not find so a 404 says whether the parent resource ID is unknown or the relationship linkage is missing. A 404 that names neither resource, and every other failure, is returned unchanged.

func EncodePKCS12Identity

func EncodePKCS12Identity(encoding PKCS12Encoding, privateKey any, certificate *x509.Certificate, password string) ([]byte, error)

EncodePKCS12Identity writes a password-protected PKCS#12 identity. The zero value selects the modern encoding.

func EnrichBuildProcessingFailure

func EnrichBuildProcessingFailure(ctx context.Context, client *asc.Client, failure BuildProcessingFailureContext, baseErr error) error

EnrichBuildProcessingFailure appends the App Store Connect processing details of the originating build upload to a terminal build-processing error. The base error is returned unchanged when no upload matches or no details are available, so a failed lookup never masks the state error.

func FetchAllAppStoreVersions added in v1.260331.0

func FetchAllAppStoreVersions(ctx context.Context, client *asc.Client, appID string, opts ...asc.AppStoreVersionsOption) ([]asc.Resource[asc.AppStoreVersionAttributes], error)

FetchAllAppStoreVersions returns all App Store versions for an app, following pagination links.

func FetchAllReviewSubmissions added in v1.260331.0

func FetchAllReviewSubmissions(ctx context.Context, client *asc.Client, appID string, opts ...asc.ReviewSubmissionsOption) ([]asc.ReviewSubmissionResource, error)

FetchAllReviewSubmissions returns all review submissions for an app, following pagination links.

func FetchAvailabilityPlatformListings added in v1.260825.0

func FetchAvailabilityPlatformListings(ctx context.Context, client *asc.Client, appID string) ([]asc.AvailabilityPlatformListing, error)

FetchAvailabilityPlatformListings returns one listing per platform: the newest live version when one exists, otherwise the newest version overall.

func FinalizeLocalizationUploadResult added in v1.260625.0

func FinalizeLocalizationUploadResult(result *asc.LocalizationUploadResult, command string)

FinalizeLocalizationUploadResult computes batch counts and writes a versioned retry artifact for failed locales. Artifact failures are retained in the result so callers can print the batch before returning an error.

func FindBundleID

func FindBundleID(ctx context.Context, client *asc.Client, identifier string) (*asc.BundleIDResponse, error)

FindBundleID returns the bundle ID whose identifier equals identifier. App Store Connect's filter[identifier] is a prefix/substring match, so the filtered list is read in full and the exact identifier is selected instead of trusting the first result.

func FlagAliasDependsOnValue

func FlagAliasDependsOnValue(f *flag.Flag) bool

FlagAliasDependsOnValue reports whether the alias f stands for a different flag depending on the value it is given.

func FlagAliasTarget

func FlagAliasTarget(f *flag.Flag, value string) (string, bool)

FlagAliasTarget returns the name of the flag that the alias f stands for when it is given value.

func FormatExactPriceDecimal

func FormatExactPriceDecimal(value *big.Rat) string

func FormatPriceDecimal

func FormatPriceDecimal(value *big.Rat, precision int) string

func FormatSubmitReadinessCreateWarning added in v1.260407.0

func FormatSubmitReadinessCreateWarning(warning SubmitReadinessCreateWarning) string

FormatSubmitReadinessCreateWarning returns the user-facing warning line.

func GetASCClient

func GetASCClient() (*asc.Client, error)

Exported wrappers for shared helpers.

func GetASCClientWithTimeout added in v1.260331.0

func GetASCClientWithTimeout(timeout time.Duration) (*asc.Client, error)

func HasAppStoreVersionInStates

func HasAppStoreVersionInStates(ctx context.Context, client *asc.Client, appID, platform string, filter AppStoreVersionStateFilter) (bool, error)

HasAppStoreVersionInStates reports whether the app has at least one app store version, optionally narrowed to one platform, whose appStoreState or appVersionState matches the filter. It stops after the first match. Every request uses ctx, so the caller's deadline bounds the whole check.

func HasCompleteEnvironmentCredentials added in v1.260825.0

func HasCompleteEnvironmentCredentials() bool

HasCompleteEnvironmentCredentials reports whether environment credentials qualify for the no-profile, no-bypass resolution fast path. It validates base64 encoding without materializing private key files.

func HasFlagValueIndirection

func HasFlagValueIndirection(value string) bool

HasFlagValueIndirection reports whether value carries one of the indirection prefixes, so callers that must not read the environment or the filesystem (help rendering) can recognize such a value without resolving it.

func HasInclude

func HasInclude(values []string, include string) bool

HasInclude returns true when include is present in values.

func HideFlagFromHelp

func HideFlagFromHelp(f *flag.Flag)

HideFlagFromHelp hides a flag from command help output while keeping it accepted at runtime.

func IncludedResourceFields

func IncludedResourceFields(resourceType string) []string

IncludedResourceFields returns the fields[type] values published for a resource type.

func InvalidValueUsageError added in v1.260819.0

func InvalidValueUsageError(parameters ...string) error

InvalidValueUsageError classifies an invalid or conflicting input after the command has already written its diagnostic to stderr. It preserves the flag.ErrHelp contract so ffcli continues to render the command usage page.

func IsAmbiguousSelection

func IsAmbiguousSelection(err error) bool

IsAmbiguousSelection reports whether err is, or wraps, an ambiguous selection error. Callers that classify local selector-resolution failures should use this instead of matching on message text.

func IsAppAvailabilityMissing

func IsAppAvailabilityMissing(err error) bool

func IsAppStoreVersionString

func IsAppStoreVersionString(value string) bool

IsAppStoreVersionString reports whether a selector is a numeric dotted version string.

func IsApplePayCertificateType

func IsApplePayCertificateType(certificateType string) bool

IsApplePayCertificateType reports whether the canonical certificate type is one of the Apple Pay types.

func IsFlagAlias

func IsFlagAlias(f *flag.Flag) bool

IsFlagAlias reports whether f is a second spelling bound with BindFlagAlias or BindBuildFlagAlias.

func IsIfExistsConflict

func IsIfExistsConflict(err error, existsCodes []string) bool

IsIfExistsConflict reports whether err is an HTTP 409 any of whose Apple error codes is one the calling command recorded as "already exists". Every other 409 (for example an unlisted STATE_ERROR.* or a relationship rejection on a command that keys on a duplicate attribute) is not an existence conflict.

Apple can report several causes for one 409, and the existence cause is not always the first: a duplicate versionString on POST /v1/appStoreVersions arrives as ENTITY_ERROR.RELATIONSHIP.INVALID ("You cannot create a new version of the App in the current state.") followed by ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE ("The version number has been previously used."), verified live against app 6759231657 on 2026-09-15. Every code in the response is therefore matched, and the command's read-back stays the decisive existence check.

func IsKnownDiagnosticCode added in v1.260819.0

func IsKnownDiagnosticCode(code DiagnosticCode) bool

IsKnownDiagnosticCode reports whether code belongs to the bounded public diagnostic taxonomy.

func IsLiveAppStoreVersion

func IsLiveAppStoreVersion(attrs asc.AppStoreVersionAttributes) bool

IsLiveAppStoreVersion reports whether a version is live on the App Store. It decides from appVersionState when Apple returns it and falls back to the deprecated appStoreState only when appVersionState is absent, matching ResolveAppStoreVersionState and the status and review next actions.

func IsLiveAppStoreVersionState

func IsLiveAppStoreVersionState(state string) bool

IsLiveAppStoreVersionState reports whether a resolved version state means the version is live on the App Store. appVersionState reports this as READY_FOR_DISTRIBUTION, while the legacy appStoreState uses READY_FOR_SALE.

func IsLiveOrPreorderAppStoreVersion

func IsLiveOrPreorderAppStoreVersion(attrs asc.AppStoreVersionAttributes) bool

IsLiveOrPreorderAppStoreVersion reports whether a version is live or listed for pre-order. Pre-order has no appVersionState spelling, so the legacy appStoreState is consulted for it even when appVersionState is present.

func IsLocalProcessFailure added in v1.260907.0

func IsLocalProcessFailure(err error) bool

IsLocalProcessFailure reports whether err contains a process-exit marker created by this package. The private marker prevents arbitrary errors from being mistaken for local child failures.

func IsLocalizationInputError added in v1.260625.0

func IsLocalizationInputError(err error) bool

IsLocalizationInputError reports malformed locale/file input that should use CLI usage exit semantics rather than a runtime failure.

func IsNumericAppID added in v1.260407.0

func IsNumericAppID(value string) bool

IsNumericAppID reports whether a value is a non-empty decimal app ID.

func IsPriceDecimal

func IsPriceDecimal(value string) bool

func IsPrintedToStderr

func IsPrintedToStderr(err error) bool

IsPrintedToStderr reports whether err carries a marker for a failure that was already written to stderr by the command or a child process.

func IsProvisioningProfilePath

func IsProvisioningProfilePath(path string) bool

IsProvisioningProfilePath reports whether path has a recognized provisioning-profile extension. The extension is only a file-type hint; callers must still parse and validate the profile contents.

func IsReportedUsageError added in v1.260816.0

func IsReportedUsageError(err error) bool

IsReportedUsageError reports whether err is an already-printed usage failure that must not trigger ffcli's full help renderer.

func IsReviewSubmissionNotCancellableError

func IsReviewSubmissionNotCancellableError(err error) bool

IsReviewSubmissionNotCancellableError reports whether err is App Store Connect refusing to cancel a review submission in its current state ("Resource state is invalid.: Resource is not in cancellable state"). It matches the specific detail, in any errors[] entry, not the generic title.

func IsTransientMutationError added in v1.260625.0

func IsTransientMutationError(parent context.Context, err error) bool

IsTransientMutationError reports whether a mutation can be retried after state readback while the parent operation remains healthy.

func IsValidationError added in v1.260701.0

func IsValidationError(err error) bool

func KeepReadOnlyRefusal

func KeepReadOnlyRefusal(kept, err error) error

KeepReadOnlyRefusal returns kept, or err when kept is nil and err is a read-only refusal. Batch commands that summarize per-item failures pass the result to NewErrorWithCause so the summary keeps the read-only exit code.

func LatestBuildUploadForWait

func LatestBuildUploadForWait(ctx context.Context, client *asc.Client, selector BuildUploadWaitSelector) (*asc.BuildUploadResponse, error)

LatestBuildUploadForWait returns the most recently uploaded build upload that matches selector, or nil when none is visible. The build number and platform filters are exact; the marketing version also matches its equivalent "1.2"/"1.2.0" spelling like build discovery does. Uploads whose upload (or, before the upload finishes, creation) time is before Since are skipped. Callers use the result only to describe a wait that has not found its build yet, so they may treat an error as "no upload information".

func LimitFlagUsage

func LimitFlagUsage(limitMax int) string

LimitFlagUsage returns the --limit help line of a list command whose pages hold at most limitMax results.

func ListAllBetaGroups

func ListAllBetaGroups(ctx context.Context, client betaGroupsClient, appID string) (*asc.BetaGroupsResponse, error)

ListAllBetaGroups fetches and paginates all beta groups for an app.

func ListAppStoreVersionsInStates

func ListAppStoreVersionsInStates(ctx context.Context, client *asc.Client, appID, platform string, filter AppStoreVersionStateFilter) ([]asc.Resource[asc.AppStoreVersionAttributes], error)

ListAppStoreVersionsInStates lists every app store version of the app, optionally narrowed to one platform, whose appStoreState or appVersionState matches the filter. Versions reported under both spellings are returned once, in the order first seen (appStoreState results first). Every request uses ctx, so the caller's deadline bounds the whole lookup.

func ListAppStoreVersionsInStatesWithRequestTimeouts

func ListAppStoreVersionsInStatesWithRequestTimeouts(ctx context.Context, client *asc.Client, appID, platform string, filter AppStoreVersionStateFilter) ([]asc.Resource[asc.AppStoreVersionAttributes], error)

ListAppStoreVersionsInStatesWithRequestTimeouts is ListAppStoreVersionsInStates for callers without their own deadline: each request, including every page and each state spelling, gets a fresh ContextWithTimeout budget, so the lookup is not capped by a single request timeout.

func LocaleRoot added in v1.260407.0

func LocaleRoot(value string) string

LocaleRoot returns the lowercased language root for a locale code.

func MapTerritoryAvailabilityIDs

func MapTerritoryAvailabilityIDs(resp *asc.TerritoryAvailabilitiesResponse) (map[string]string, error)

MapTerritoryAvailabilityIDs maps territory IDs to territory-availability IDs.

func MapVersionLocalizationStrings

func MapVersionLocalizationStrings(attrs asc.AppStoreVersionLocalizationAttributes) map[string]string

MapVersionLocalizationStrings converts version localization attributes into .strings keys.

func MarkAmbiguousSelectionSample

func MarkAmbiguousSelectionSample(err error) error

MarkAmbiguousSelectionSample marks an ambiguity whose candidates came from a response that advertises another page. The returned error keeps its concrete type and wrapping chain so callers can still inspect the candidates and classify the failure.

func MarkUploadDeadline

func MarkUploadDeadline(err error) error

MarkUploadDeadline marks a deadline error as an upload deadline. Callers use it only after checking that their upload context, not a request context, expired. Other errors are returned unchanged.

func MediaUploadTimeoutForWork

func MediaUploadTimeoutForWork(files int, bytes int64) time.Duration

MediaUploadTimeoutForWork returns the default deadline for uploading files totaling bytes and waiting for App Store Connect to process them.

func MergeNextURLQuery added in v1.260331.0

func MergeNextURLQuery(next string, additions url.Values) (string, error)

MergeNextURLQuery reapplies required query parameters to a validated next URL.

func MissingRequiredUsageError added in v1.260628.0

func MissingRequiredUsageError(parameters ...string) error

MissingRequiredUsageError classifies a required-input failure after the command has already written its diagnostic to stderr.

func MissingSubmitRequiredLocalizationFieldsWithOptions

func MissingSubmitRequiredLocalizationFieldsWithOptions(attrs asc.AppStoreVersionLocalizationAttributes, opts SubmitReadinessOptions) []string

MissingSubmitRequiredLocalizationFieldsWithOptions returns missing metadata fields that block App Store submission, with configurable checks.

func NewAvailabilityRemoveFromSaleCommand added in v1.260819.0

func NewAvailabilityRemoveFromSaleCommand(config AvailabilityRemoveFromSaleCommandConfig) *ffcli.Command

NewAvailabilityRemoveFromSaleCommand builds a command that makes every existing territory unavailable while preserving the app's new-territory policy.

func NewAvailabilitySetCommand

func NewAvailabilitySetCommand(config AvailabilitySetCommandConfig) *ffcli.Command

NewAvailabilitySetCommand builds a shared availability set command.

func NewCategoriesSetCommand

func NewCategoriesSetCommand(config CategoriesSetCommandConfig) *ffcli.Command

NewCategoriesSetCommand builds a categories set command with shared behavior.

func NewErrorWithCause added in v1.260722.0

func NewErrorWithCause(err, cause error) error

NewErrorWithCause preserves err's rendered message and classification while retaining an additional cause for errors.Is/errors.As and telemetry.

func NewNotConfiguredReportedError

func NewNotConfiguredReportedError(err error) error

NewNotConfiguredReportedError classifies an already-printed expected negative for a resource that has not been configured yet, such as an app without an availability record. It maps to the validation exit code and the state_not_ready diagnostic instead of a not-found API failure.

func NewPendingError

func NewPendingError(message string) error

NewPendingError returns an already-reported ErrPending outcome. The root renderer prints nothing for it; the command must have written its pending result and any stderr notice before returning it.

func NewPriceSchedulePPPCommand

func NewPriceSchedulePPPCommand(config PriceSchedulePPPCommandConfig) *ffcli.Command

NewPriceSchedulePPPCommand builds a purchasing-power-parity command for resources priced with price schedules.

func NewPricingSetCommand

func NewPricingSetCommand(config PricingSetCommandConfig) *ffcli.Command

NewPricingSetCommand builds a pricing set command with shared behavior.

func NewProcessExitError added in v1.260816.0

func NewProcessExitError(code int) error

NewProcessExitError preserves a child process exit code without duplicating the child's stderr through the root error renderer.

func NewProcessExitErrorWithCause added in v1.260907.0

func NewProcessExitErrorWithCause(code int, cause error) error

NewProcessExitErrorWithCause preserves a local child exit status while retaining the typed child failure for errors.Is/errors.As and telemetry.

func NewReportedError

func NewReportedError(err error) error

NewReportedError wraps an error whose result the command already printed to stdout. The root prints err once to stderr as an "Error:" line.

func NewReportedUsageError added in v1.260816.0

func NewReportedUsageError(kind UsageErrorKind, message string) error

NewReportedUsageError classifies an already-printed usage failure without wrapping flag.ErrHelp, which would cause ffcli to print the command's full usage page. The returned error maps to usage exit code 2.

func NewReviewSubmissionNotCancellableError

func NewReviewSubmissionNotCancellableError(submissionID string, state asc.ReviewSubmissionState, cancelErr error) error

NewReviewSubmissionNotCancellableError explains a refused cancel from a state the caller already read. It returns cancelErr unchanged when state is empty.

func NewStderrReportedError

func NewStderrReportedError(err error) error

NewStderrReportedError wraps an error the command already printed to stderr, so the root prints nothing more for it.

func NewValidationError added in v1.260701.0

func NewValidationError(err error) error

NewValidationError wraps an error that represents local/domain validation.

func NewValidationReportedError added in v1.260701.0

func NewValidationReportedError(err error) error

NewValidationReportedError wraps an already printed validation result.

func NewVersionLocalizationImportCommand

func NewVersionLocalizationImportCommand(config VersionLocalizationImportConfig) *ffcli.Command

NewVersionLocalizationImportCommand builds a command that creates missing locales and updates changed ones for a version from one JSON file.

func NormalizeASCTerritoryCSV added in v1.260407.0

func NormalizeASCTerritoryCSV(value string) ([]string, error)

func NormalizeAppStoreLocalizationLocale added in v1.260407.0

func NormalizeAppStoreLocalizationLocale(value string) (string, error)

NormalizeAppStoreLocalizationLocale validates locale syntax and canonicalizes known codes. Unknown but well-formed locale codes are preserved for forward compatibility.

func NormalizeAppStoreVersionPlatform

func NormalizeAppStoreVersionPlatform(value string) (string, error)

NormalizeAppStoreVersionPlatform validates a single platform value.

func NormalizeAppStoreVersionPlatforms

func NormalizeAppStoreVersionPlatforms(values []string) ([]string, error)

NormalizeAppStoreVersionPlatforms validates multiple platform values.

func NormalizeAppStoreVersionStates

func NormalizeAppStoreVersionStates(values []string) ([]string, error)

NormalizeAppStoreVersionStates validates multiple state values.

func NormalizeBetaGroupName

func NormalizeBetaGroupName(name string) string

NormalizeBetaGroupName collapses every Unicode space run to one ASCII space. App Store Connect names each app's default internal group with a non-breaking space, which users cannot type. Resolvers try exact names first and fall back to normalized names.

func NormalizeBundleIDPlatform added in v1.260807.0

func NormalizeBundleIDPlatform(value string) (asc.BundleIDPlatform, error)

NormalizeBundleIDPlatform validates and normalizes a BundleIdPlatform value.

func NormalizeDate

func NormalizeDate(value, flagName string) (string, error)

func NormalizeEnumToken

func NormalizeEnumToken(value string) string

NormalizeEnumToken normalizes enum-like flag values by uppercasing and converting separators to underscore form.

func NormalizeLocaleCode added in v1.260407.0

func NormalizeLocaleCode(value string) string

NormalizeLocaleCode trims whitespace and canonicalizes separators for locale codes.

func NormalizeLocalizationType

func NormalizeLocalizationType(value string) (string, error)

func NormalizeOfferCodeEnvironment

func NormalizeOfferCodeEnvironment(value string) (string, error)

NormalizeOfferCodeEnvironment validates the --environment flag of one-time use offer code creation. An empty value stays empty so the attribute is omitted.

func NormalizeOutputFormat

func NormalizeOutputFormat(format string) string

NormalizeOutputFormat lowercases format and canonicalizes aliases.

func NormalizePlatform

func NormalizePlatform(value string) (asc.Platform, error)

NormalizePlatform validates and normalizes a platform string.

func NormalizeReviewSubmissionStates

func NormalizeReviewSubmissionStates(values []string) ([]string, error)

NormalizeReviewSubmissionStates validates multiple review submission state values.

func NormalizeSelection

func NormalizeSelection(value string, allowed []string, flagName string) ([]string, error)

NormalizeSelection validates comma-separated values against an allow-list.

func NormalizeSubscriptionPlanType

func NormalizeSubscriptionPlanType(value, source string) (asc.SubscriptionPlanType, error)

NormalizeSubscriptionPlanType validates a plan type, naming source in the error.

func NormalizeTestNotesForCommand

func NormalizeTestNotesForCommand(w io.Writer, notes string) (string, error)

NormalizeTestNotesForCommand normalizes What to Test notes for a command, writing the one-line notice or the usage diagnostic to w. It returns the text the caller must submit and store in any retry payload.

func NormalizeVersionMetadataCopyFields

func NormalizeVersionMetadataCopyFields(value, flagName string) ([]string, error)

NormalizeVersionMetadataCopyFields validates a comma-separated field list against version localization keys.

func OpenExistingNoFollow

func OpenExistingNoFollow(path string) (*os.File, error)

OpenExistingNoFollow opens an existing file without following symlinks.

func OpenNewFileNoFollow

func OpenNewFileNoFollow(path string, perm os.FileMode) (*os.File, error)

OpenNewFileNoFollow creates a new file without following symlinks. Uses O_EXCL to prevent overwriting existing files and O_NOFOLLOW to prevent symlink attacks.

func OpenValidatedIPAPath added in v1.260819.0

func OpenValidatedIPAPath(ipaPath string) (*os.File, os.FileInfo, error)

OpenValidatedIPAPath opens and validates an IPA without following a symlink. The returned handle pins the validated file across the upload lifecycle.

func OpenValidatedPKGPath added in v1.260819.0

func OpenValidatedPKGPath(pkgPath string) (*os.File, os.FileInfo, error)

OpenValidatedPKGPath opens and validates a PKG without following a symlink. The returned handle pins the validated file across the upload lifecycle.

func OrNA

func OrNA(value string) string

OrNA trims a string and returns "n/a" when empty.

func ParseBoolFlag

func ParseBoolFlag(value, flagName string) (bool, error)

ParseBoolFlag parses common bool-like flag values and returns a usage-style error with the provided flagName when parsing fails.

func ParseBuildTimestamp added in v1.260404.0

func ParseBuildTimestamp(value string) (time.Time, error)

ParseBuildTimestamp parses ASC uploadedDate values used across build helpers.

func ParseInterspersedFlags

func ParseInterspersedFlags(fs *flag.FlagSet, args []string) ([]string, error)

ParseInterspersedFlags applies flags that appear after positional arguments to fs and returns the remaining positional arguments in order. The standard flag package stops at the first positional token, so commands with a positional payload call this from Exec to accept `asc cmd VALUE --flag`.

A leading `--` was already consumed by flag parsing, so when the first remaining argument still starts with a dash it was escaped and the whole list is returned as positional arguments. A later `--` ends flag parsing.

func ParseOptionalBoolFlag

func ParseOptionalBoolFlag(name, raw string) (*bool, error)

ParseOptionalBoolFlag parses an optional boolean flag value.

func ParseRFC3339Date added in v1.260331.0

func ParseRFC3339Date(value string) (time.Time, bool)

ParseRFC3339Date parses a timestamp in RFC3339 or RFC3339Nano form.

func PlanPriceLadderRow

func PlanPriceLadderRow(
	source ResolvedPriceRow,
	current *ResolvedPriceRow,
	multiplier *big.Rat,
	candidates []PriceLadderCandidate,
	candidatesErr error,
	rounding PriceRounding,
) asc.SubscriptionPricingDeriveRow

PlanPriceLadderRow plans one territory: source price × multiplier resolved on the territory's candidate ladder. A nil multiplier marks the territory skipped, keeping its current price.

func PlatformList

func PlatformList() []string

PlatformList returns the allowed platform values.

func PrepareBuildUpload added in v1.260404.0

func PrepareBuildUpload(ctx context.Context, client *asc.Client, appID string, fileInfo os.FileInfo, version, buildNumber string, platform asc.Platform, uti asc.UTI) (*asc.BuildUploadResponse, *asc.BuildUploadFileResponse, error)

PrepareBuildUpload creates the build upload and file reservation records used by publish/build upload flows before the binary is transferred.

func PriceActiveOn

func PriceActiveOn(start, end *time.Time, date time.Time) bool

PriceActiveOn reports whether a scheduled price applies on date, a pricing date from PricingDate. start and end are the price's schedule dates as midnight UTC, or nil when unbounded. Start dates are inclusive and end dates are exclusive: App Store Connect ends one price on the date the next one starts.

func PricePointTerritoryID

func PricePointTerritoryID(raw json.RawMessage) string

PricePointTerritoryID returns the territory ID from a price point's relationships, or "" when the territory relationship was not included.

func PricingDate

func PricingDate(now time.Time) time.Time

PricingDate returns the App Store Connect pricing date that contains now: its US Pacific calendar day. The date is returned as midnight UTC so it compares directly with schedule dates parsed from YYYY-MM-DD.

func PrimaryIDFlagName

func PrimaryIDFlagName(flagSet *flag.FlagSet) (string, bool)

PrimaryIDFlagName returns the single primary identifier flag that flagSet defines and the caller has not already passed. It reports false when the command defines none of them, when it defines several (with more than one candidate the intended flag would be a guess), and when the one candidate is already set, because a caller who wrote `--app APP_ID` did not mean the stray token as a second app.

func PrintSubmitReadinessCreateWarnings added in v1.260407.0

func PrintSubmitReadinessCreateWarnings(w io.Writer, warnings []SubmitReadinessCreateWarning) error

PrintSubmitReadinessCreateWarnings emits normalized warnings to the writer.

func ProcessExitCode added in v1.260816.0

func ProcessExitCode(err error) (int, bool)

ProcessExitCode reports an exact child-process exit code only for errors created by NewProcessExitError. The private marker prevents collisions with ordinary command execution errors elsewhere in asc.

func ProvisioningProfileExtension

func ProvisioningProfileExtension(platform, profileType string) string

ProvisioningProfileExtension returns the conventional extension for a profile. A known platform takes precedence; the profile type is used as a fallback because profile creation preflight runs before the API returns the created resource's platform attribute.

func ProvisioningProfileExtensionForPlatforms

func ProvisioningProfileExtensionForPlatforms(platforms []string, profileType string) string

ProvisioningProfileExtensionForPlatforms returns the conventional extension for a profile whose parsed payload may advertise more than one platform. macOS wins when present; an unknown or empty platform preserves the legacy iOS-compatible default.

func ReadLocalizationStrings

func ReadLocalizationStrings(inputPath string, locales []string) (map[string]map[string]string, error)

func RecordAPIOperation

func RecordAPIOperation(ctx context.Context, method, path string)

RecordAPIOperation records the method and request path of an `asc api` invocation in ctx's record, if it has one.

func RecordAPIQueryNames

func RecordAPIQueryNames(ctx context.Context, query url.Values)

RecordAPIQueryNames records the names of the query parameters an `asc api` request sends in ctx's record, if it has one.

func RelationshipTypeFlagUsage

func RelationshipTypeFlagUsage(values []string) string

RelationshipTypeFlagUsage renders the --type flag help for a links command so the help text enumerates every accepted relationship type.

func RelationshipTypeValues

func RelationshipTypeValues(values []string) string

RelationshipTypeValues renders the accepted --type values so flag help and both --type usage errors always agree on the list a links command accepts.

func ReportFile

func ReportFile() string

ReportFile returns the configured report file path.

func ReportFormat

func ReportFormat() string

ReportFormat returns the configured report format.

func RequireAppStoreBuildAudience

func RequireAppStoreBuildAudience(buildResp *asc.BuildResponse) error

RequireAppStoreBuildAudience rejects builds restricted to internal testing.

func RequireConfirm

func RequireConfirm(confirm bool) error

RequireConfirm enforces --confirm on a destructive command. Without it, it prints "Error: --confirm is required" to stderr and returns a usage error with the required-input diagnostic. Commands check it after their other required flags and before any request, file read or prompt.

func RequiredFlag

func RequiredFlag(name string) error

RequiredFlag reports a missing required flag: it prints "Error: <name> is required" to stderr and returns MissingRequiredUsageError(name).

func ResetDefaultOutputFormat

func ResetDefaultOutputFormat()

ResetDefaultOutputFormat clears the cached ASC_DEFAULT_OUTPUT value so that the next DefaultOutputFormat call re-reads it. Tests only.

func ResetEquivalentVersionNotesForTest

func ResetEquivalentVersionNotesForTest()

ResetEquivalentVersionNotesForTest forgets which equivalent-version notes were already printed, so each in-process command run reports them again.

func ResetTierCacheForTest added in v1.260325.0

func ResetTierCacheForTest(dir string)

ResetTierCacheForTest empties dir and routes tier-cache reads and writes to it.

func ResolveAppID

func ResolveAppID(appID string) string

func ResolveAppIDWithExactLookup

func ResolveAppIDWithExactLookup(ctx context.Context, client appLookupClient, appID string) (string, error)

ResolveAppIDWithExactLookup takes an already-resolved app identifier and looks it up by exact bundle ID and exact app name only. If no exact match exists and the value is numeric, it falls back to treating it as an App Store Connect app ID.

func ResolveAppIDWithLookup

func ResolveAppIDWithLookup(ctx context.Context, client appLookupClient, appID string) (string, error)

ResolveAppIDWithLookup takes an already-resolved app identifier and, when non-numeric, looks it up by exact bundle ID, exact app name, then legacy fuzzy-name matching when unique.

func ResolveAppStoreVersionID

func ResolveAppStoreVersionID(ctx context.Context, client *asc.Client, appID, version, platform string) (string, error)

ResolveAppStoreVersionID finds a version ID by version string and platform.

func ResolveAppStoreVersionIDAndState

func ResolveAppStoreVersionIDAndState(ctx context.Context, client *asc.Client, appID, version, platform string) (string, string, error)

ResolveAppStoreVersionIDAndState finds a version ID and state by version string and platform.

func ResolveAppStoreVersionState

func ResolveAppStoreVersionState(attrs asc.AppStoreVersionAttributes) string

ResolveAppStoreVersionState prefers the app version state when available.

func ResolveBundleInfoForIPA added in v1.260404.0

func ResolveBundleInfoForIPA(ipaPath, version, buildNumber string) (string, string, error)

ResolveBundleInfoForIPA fills missing version/build-number values from the IPA and preserves the existing CLI-facing error messages.

func ResolveFreeAppPricePoint added in v1.260328.0

func ResolveFreeAppPricePoint(ctx context.Context, client *asc.Client, appID, territory string) (string, error)

ResolveFreeAppPricePoint finds the free ($0) price point ID for an app in a territory.

func ResolveIAPID added in v1.260404.0

func ResolveIAPID(ctx context.Context, client iapSelectorClient, appID, selector string) (string, error)

ResolveIAPID resolves an in-app purchase selector to its canonical ASC ID.

func ResolveIfExistsConflict

func ResolveIfExistsConflict[T any](mode IfExistsMode, createErr error, existsCodes []string, lookup func() (T, bool, error)) (T, bool, error)

ResolveIfExistsConflict applies the existence rule for a failed create:

  1. The failure must be an HTTP 409 whose Apple error code is one of existsCodes (see IsIfExistsConflict).
  2. lookup must read the resource back by its natural key.

Only when both hold is the conflict treated as "already exists" and the existing resource returned with handled=true. Every other outcome returns createErr unchanged so state conflicts, unrelated 409s, and conflicts whose read-back finds nothing keep failing exactly as they do with --if-exists fail. A read-back that fails for a reason other than not-found is appended to the original conflict so the caller sees both.

func ResolveOwnedAppStoreVersionByID added in v1.260404.0

func ResolveOwnedAppStoreVersionByID(ctx context.Context, client *asc.Client, appID, versionID, platform string) (asc.Resource[asc.AppStoreVersionAttributes], error)

ResolveOwnedAppStoreVersionByID fetches a version by ID and validates its app ownership and optional platform.

func ResolvePricePointByPrice

func ResolvePricePointByPrice(tiers []TierEntry, price string) (string, error)

ResolvePricePointByPrice finds the price point ID for a given customer price.

func ResolvePricePointByTier

func ResolvePricePointByTier(tiers []TierEntry, tier int) (string, error)

ResolvePricePointByTier finds the price point ID for a given tier number.

func ResolveProfileName

func ResolveProfileName() string

func ResolveReportOutputPaths

func ResolveReportOutputPaths(outputPath, defaultCompressed, decompressedExt string, decompress bool) (string, string)

ResolveReportOutputPaths returns compressed/decompressed paths for reports.

func ResolveSubscriptionID added in v1.260404.0

func ResolveSubscriptionID(ctx context.Context, client subscriptionSelectorClient, appID, selector string) (string, error)

ResolveSubscriptionID resolves a subscription selector to its canonical ASC ID.

func ResolveTimeoutSetting

func ResolveTimeoutSetting(setting TimeoutSetting, defaultTimeout time.Duration) time.Duration

ResolveTimeoutSetting returns the duration the user set for setting, or defaultTimeout when it is unset or invalid.

func ResolveVersionMetadataCopyFields

func ResolveVersionMetadataCopyFields(copyFields, excludeFields []string) ([]string, error)

ResolveVersionMetadataCopyFields applies explicit includes/excludes to the supported metadata field set.

func ResourceIDFromValue

func ResourceIDFromValue(value, resourceType string) (string, error)

ResourceIDFromValue accepts a bare App Store Connect resource ID or the resource's API self-link (for example the links.self value from JSON output or a webhook delivery) and returns the bare ID.

Only URLs on an API host whose path is exactly /v<n>/<type>/<id> are accepted. When resourceType is non-empty the <type> segment must match it. Values that are not http(s) URLs are returned trimmed and otherwise unchanged so bundle identifiers, product IDs, names, and other selector shapes keep working.

func RetryReadWithFreshTimeout added in v1.260625.0

func RetryReadWithFreshTimeout[T any](ctx context.Context, read func(context.Context) (T, error)) (T, error)

RetryReadWithFreshTimeout retries child request deadlines with a fresh timeout budget while the operation's parent context remains healthy.

func RetryReadWithFreshTimeoutWith

func RetryReadWithFreshTimeoutWith[T any](ctx context.Context, d *Deps, read func(context.Context) (T, error)) (T, error)

RetryReadWithFreshTimeoutWith is RetryReadWithFreshTimeout with each attempt's deadline from d.Timeout and the waits between attempts on d.After.

func ReviewScreenshotDeliveryError

func ReviewScreenshotDeliveryError(group, screenshotID string, details []asc.StateDetail) error

ReviewScreenshotDeliveryError reports a review screenshot that App Store Connect rejected after upload as invalid --file input. The failed screenshot stays attached and blocks a new upload, so the message names the delete command of group.

func RewriteCommandTreePath

func RewriteCommandTreePath(cmd *ffcli.Command, currentPrefix, replacementPrefix string) *ffcli.Command

RewriteCommandTreePath rewrites usage/help path prefixes for an existing command tree.

func RewriteUsageMessage added in v1.260904.0

func RewriteUsageMessage(ctx context.Context, message string) string

RewriteUsageMessage applies the command-path rewrites carried by ctx to message. A context without rewrites returns message unchanged.

func RootFlagsForReinvocation

func RootFlagsForReinvocation() (args []string, ok bool)

RootFlagsForReinvocation returns the root-level flags that were explicitly set, in binding order, so a command can print a re-invocation that keeps the caller's behavior instead of silently dropping flags such as --strict-auth. Values are rendered with ShellQuote; ok is false when any of them cannot be rendered as a copyable argument, so callers omit the suggestion entirely rather than print a command that would run with a different value.

func SafeWriteFileNoSymlink(path string, perm os.FileMode, overwrite bool, tempPattern string, backupPattern string, write func(*os.File) (int64, error)) (int64, error)

SafeWriteFileNoSymlink writes a file to path without following symlinks and with an optional overwrite mode that preserves the original destination until the new file is fully written.

When overwrite is false, the destination must not already exist. When overwrite is true, we refuse to overwrite symlinks and we use temp+rename; if rename fails because the destination exists (notably on Windows), we fall back to a safe replace that uses a backup file to preserve the original if the final move fails.

func SafeWriteFileNoSymlinkWithPreparationAndCreator added in v1.260904.0

func SafeWriteFileNoSymlinkWithPreparationAndCreator(path string, perm os.FileMode, overwrite bool, tempPattern string, backupPattern string, prepare func(*os.File) error, create func(*os.Root, string, os.FileMode) (*os.File, error), write func(*os.File) (int64, error)) (int64, error)

SafeWriteFileNoSymlinkWithPreparationAndCreator is the protected writer variant with an optional rooted temporary-file creator. The creator is used only to add platform-specific creation security; generated names, rooted placement, exclusive creation, and post-open identity checks remain owned by secureopen. Protected no-overwrite writes do not use a copy fallback.

func SafeWriteFileNoSymlinkWithPreparationAndCreatorInRoot added in v1.260904.0

func SafeWriteFileNoSymlinkWithPreparationAndCreatorInRoot(parent *os.Root, displayPath, base string, perm os.FileMode, overwrite bool, tempPattern string, backupPattern string, prepare func(*os.File) error, create func(*os.Root, string, os.FileMode) (*os.File, error), write func(*os.File) (int64, error)) (int64, error)

SafeWriteFileNoSymlinkWithPreparationAndCreatorInRoot is the protected writer operating through an already-pinned parent directory handle. Callers that validated the destination's parent chain with a no-follow walk pass the resulting root here, so no path-based directory resolution runs between validation and publication. displayPath is used only for error messages; base must be a single path element inside parent.

func SanitizeTerminal

func SanitizeTerminal(input string) string

SanitizeTerminal removes characters interpreted by terminals and log viewers.

func SaveTierCache

func SaveTierCache(appID, territory string, tiers []TierEntry) error

SaveTierCache writes tier data to the cache file.

func SelectBestAppInfoID

func SelectBestAppInfoID(appInfos *asc.AppInfosResponse) string

SelectBestAppInfoID chooses the most editable app info for updates.

func SelectedProfile

func SelectedProfile() string

SelectedProfile returns the current profile override.

func SelectorFlagForResource

func SelectorFlagForResource(resourceName string) string

SelectorFlagForResource names the stable-selector flag that accepts an explicit ASC ID for a resource kind resolved by ResolveIAPID, ResolveSubscriptionID, or ResolveExactSelectorCandidate. Commands that bind a different flag wrap the resolver error with WithSelectorFlag.

func SelectorNeedsLookup added in v1.260404.0

func SelectorNeedsLookup(value string) bool

SelectorNeedsLookup reports whether a selector needs app-scoped lookup instead of direct ASC ID passthrough.

func SetASCClientFactoryForTesting added in v1.260722.0

func SetASCClientFactoryForTesting(fn func() (*asc.Client, error)) func()

SetASCClientFactoryForTesting replaces the general command ASC client factory. It returns a restore function to reset the previous handler.

func SetAvailabilityClientFactory added in v1.260722.0

func SetAvailabilityClientFactory(fn func() (*asc.Client, error)) func()

SetAvailabilityClientFactory replaces the ASC client factory for availability tests. It returns a restore function to reset the previous handler.

func SetBuildUploadFailureDiagnosticsForTesting

func SetBuildUploadFailureDiagnosticsForTesting(fn func(context.Context, *asc.Client, string, *asc.BuildUploadResponse) (string, error)) func()

SetBuildUploadFailureDiagnosticsForTesting overrides build failure enrichment. Tests only.

func SetJUnitReport added in v1.260831.0

func SetJUnitReport(report *JUnitReport)

SetJUnitReport registers a command-produced JUnit report for the current invocation. The root runner consumes it after the command returns so command-specific reports can coexist with the generic command report.

func SetNoProgress

func SetNoProgress(value bool)

SetNoProgress sets progress suppression (tests only).

func SetReportFile

func SetReportFile(path string)

SetReportFile sets the report file path (for testing).

func SetReportFormat

func SetReportFormat(format string)

SetReportFormat sets the report format (for testing).

func SetSelectedProfile

func SetSelectedProfile(value string)

SetSelectedProfile sets the current profile override (tests only).

func ShellCommand

func ShellCommand(ctx context.Context, command string) *exec.Cmd

ShellCommand runs a user-supplied command line through the platform shell, without login-shell startup files whose output would precede the command's.

func ShellQuote

func ShellQuote(value string) (string, bool)

ShellQuote renders value as one literal argument so a printed command can be copied into the user's shell unchanged. ok reports whether that is possible. asc cannot know which shell invoked it, so it only advertises a rendering that every plausible shell for the platform reads identically:

  • On darwin and linux, single quotes suppress all expansion, and an embedded apostrophe has one escaping that sh, bash, and zsh all accept.
  • On Windows, double quotes group an argument in PowerShell, cmd.exe, and Git Bash alike, but those shells disagree on single quotes, expansion, and escaping, so a value containing any character one of them treats specially has no neutral rendering.

ok is false for those values, and for control characters, bidi marks, and invalid UTF-8, which cannot be both inert in a terminal and byte-exact. Callers must then omit the value instead of printing an approximation.

func ShellQuoteForOS

func ShellQuoteForOS(value, goos string) (string, bool)

ShellQuoteForOS applies ShellQuote's byte-exact rendering contract for the requested target platform. It exists for callers that already make an explicit platform decision and for deterministic cross-platform tests.

func ShouldPreferLatestReviewSubmission added in v1.260331.0

func ShouldPreferLatestReviewSubmission(current, best asc.ReviewSubmissionResource) bool

ShouldPreferLatestReviewSubmission reports whether current should win over best when selecting the most relevant submission.

func SnapshotImageFile

func SnapshotImageFile(source *os.File, size int64) (*os.File, func(), error)

SnapshotImageFile copies the selected image into a private temporary file before any checksum or upload work begins. Hashing and uploading the source pathname independently would allow an in-place rewrite between those reads to commit a checksum for different bytes than the upload sent.

func SortResolvedPrices added in v1.260331.0

func SortResolvedPrices(rows []ResolvedPriceRow)

SortResolvedPrices orders prices deterministically for stable output.

func SpinnerEnabled

func SpinnerEnabled() bool

SpinnerEnabled reports whether the CLI should render an indeterminate spinner on stderr for the current run.

Requirements:

  • stderr-only (handled by WithSpinner)
  • TTY-gated (stdout + stderr)
  • opt-out via ASC_SPINNER_DISABLED (invalid => disabled)
  • disabled when stderr is expected to be noisy (debug/retry logs)

func SplitCSV

func SplitCSV(value string) []string

func SplitCSVUpper

func SplitCSVUpper(value string) []string

func SplitUniqueCSV

func SplitUniqueCSV(value string) []string

func StrictAuthEnabled added in v1.260825.0

func StrictAuthEnabled() bool

StrictAuthEnabled reports whether mixed credential sources must fail.

func SubmitIncompleteLocaleWarningWithOptions added in v1.260407.0

func SubmitIncompleteLocaleWarningWithOptions(locale string, attrs asc.AppStoreVersionLocalizationAttributes, opts SubmitReadinessOptions) string

SubmitIncompleteLocaleWarningWithOptions returns a user-facing warning when a locale is missing submit-required metadata fields under the provided rules.

func SuggestCanonicalLocaleCodes added in v1.260407.0

func SuggestCanonicalLocaleCodes(value string, supported []string, canonicalByFold map[string]string) []string

SuggestCanonicalLocaleCodes returns deduplicated canonical locale suggestions for fuzzy input.

func SupportedMetadataLocales added in v1.260407.0

func SupportedMetadataLocales() []string

SupportedMetadataLocales returns the metadata-compatible subset of the shared App Store localization catalog.

func UploadAppInfoLocalizations

func UploadAppInfoLocalizations(ctx context.Context, client appInfoLocalizationClient, appInfoID string, valuesByLocale map[string]map[string]string, dryRun bool) ([]asc.LocalizationUploadLocaleResult, error)

func UpsertBetaBuildLocalization

func UpsertBetaBuildLocalization(ctx context.Context, client *asc.Client, buildID, locale, notes string, opts UpsertBetaBuildLocalizationOptions) (*asc.BetaBuildLocalizationResponse, error)

UpsertBetaBuildLocalization creates or updates a beta build localization, first ensuring the app has a TestFlight app localization for the locale.

func UsageDeclaresOperands

func UsageDeclaresOperands(usage string) bool

UsageDeclaresOperands reports whether a command's own ShortUsage declares positional operands, as `asc search [flags] <query>` does and `asc apps view --id APP_ID` does not.

Only the tokens before the first flag spelling are operands. Everything from the first flag onward is either a flag or a flag value, and a value placeholder (`<bash|zsh|fish>` in `asc completion --shell <bash|zsh|fish>`) is not an operand. A standalone `--` terminator always introduces operands, because the tokens after it are handed to a child process verbatim.

func UsageError

func UsageError(message string) error

UsageError prints a CLI validation error and returns flag.ErrHelp so callers map the failure to usage exit code semantics.

func UsageErrorf

func UsageErrorf(format string, args ...any) error

UsageErrorf formats and returns a usage-class validation error.

func ValidateAppInfoLocalizationKeys

func ValidateAppInfoLocalizationKeys(locale string, values map[string]string) error

ValidateAppInfoLocalizationKeys validates .strings keys for an app-info localization locale.

func ValidateAppInfoLocalizationValueSet added in v1.260625.0

func ValidateAppInfoLocalizationValueSet(valuesByLocale map[string]map[string]string) error

ValidateAppInfoLocalizationValueSet validates every locale before auth or remote state is read.

func ValidateAppStoreVersionStateFilterCombination added in v1.260601.0

func ValidateAppStoreVersionStateFilterCombination(values []string) error

ValidateAppStoreVersionStateFilterCombination rejects state combinations that cannot be represented by one App Store Connect version-list request.

func ValidateBoundOutputFlags

func ValidateBoundOutputFlags(fs *flag.FlagSet) error

ValidateBoundOutputFlags validates any output-format flags bound via the shared output helpers on the provided flagset.

func ValidateBuildLocalizationLocale

func ValidateBuildLocalizationLocale(locale string) error

ValidateBuildLocalizationLocale validates a locale string.

func ValidateBuildLocalizationLocales

func ValidateBuildLocalizationLocales(locales []string) error

ValidateBuildLocalizationLocales validates multiple locale strings.

func ValidateFinitePriceFlag

func ValidateFinitePriceFlag(flagName, value string) error

ValidateFinitePriceFlag validates a numeric flag value that must be finite.

func ValidateIPAPath added in v1.260404.0

func ValidateIPAPath(ipaPath string) (os.FileInfo, error)

ValidateIPAPath ensures an IPA path points to a non-empty regular file and rejects symlinks so upload commands don't dereference unexpected files.

func ValidateInclude added in v1.260625.0

func ValidateInclude(value string, allowed ...string) error

ValidateInclude validates a comma-separated --include value against the set of allowed relationship names. An empty value is valid (no includes).

func ValidateNextURL

func ValidateNextURL(next string) error

func ValidateOutputFormat

func ValidateOutputFormat(format string, pretty bool) (string, error)

func ValidateOutputFormatAllowed

func ValidateOutputFormatAllowed(format string, pretty bool, allowed ...string) (string, error)

func ValidatePKGPath added in v1.260819.0

func ValidatePKGPath(pkgPath string) (os.FileInfo, error)

ValidatePKGPath ensures a PKG path points to a non-empty regular file and rejects symlinks before an upload reservation is created.

func ValidatePPPScheduleSnapshot

func ValidatePPPScheduleSnapshot(snapshot PPPScheduleSnapshot, now func() time.Time) error

ValidatePPPScheduleSnapshot fails closed before reconstructing a schedule. now is the clock that decides today's pricing date.

func ValidatePriceSelectionFlags

func ValidatePriceSelectionFlags(pricePoint string, tier int, price string, free ...bool) error

ValidatePriceSelectionFlags checks that --price-point, --tier, --price, and --free are mutually exclusive. Returns a usage-style error if more than one is set. Each failure carries a structured diagnostic so callers can classify it without re-deriving which rule was violated; the rendered messages are unchanged.

func ValidateReportFlags

func ValidateReportFlags() error

ValidateReportFlags validates the CI report flags and returns an error if invalid.

func ValidateSort

func ValidateSort(value string, allowed ...string) error

func ValidateVersionLocalizationAttributes added in v1.260407.0

func ValidateVersionLocalizationAttributes(attrs asc.AppStoreVersionLocalizationAttributes) error

ValidateVersionLocalizationAttributes validates version localization attributes that the App Store Connect request contract makes locally knowable.

func ValidateVersionLocalizationAttributesByLocale added in v1.260407.0

func ValidateVersionLocalizationAttributesByLocale(valuesByLocale map[string]asc.AppStoreVersionLocalizationAttributes) error

ValidateVersionLocalizationAttributesByLocale validates attribute values for all locales.

func ValidateVersionLocalizationKeys

func ValidateVersionLocalizationKeys(locale string, values map[string]string) error

ValidateVersionLocalizationKeys validates .strings keys for a version localization locale.

func ValidateVersionLocalizationValueSet added in v1.260407.0

func ValidateVersionLocalizationValueSet(valuesByLocale map[string]map[string]string) error

ValidateVersionLocalizationValueSet validates value maps for all locales.

func ValidateVersionLocalizationValues added in v1.260407.0

func ValidateVersionLocalizationValues(locale string, values map[string]string) error

ValidateVersionLocalizationValues validates .strings keys and value limits for one locale.

func VerifyBuildUploadAfterCommit

func VerifyBuildUploadAfterCommit(ctx context.Context, client *asc.Client, appID, uploadID string, pollInterval, verifyTimeout time.Duration) (string, error)

VerifyBuildUploadAfterCommit briefly watches a newly committed upload for immediate App Store Connect failures. It returns the ID of the build the upload created once App Store Connect links it, which ends the watch early. It returns an empty build ID and nil error on timeout so the caller can keep the default asynchronous success behavior when no failure is observed during the bounded verification window.

func VersionLocalizationKeys

func VersionLocalizationKeys() []string

VersionLocalizationKeys returns the supported app store version localization keys.

func VersionLocalizationValue

func VersionLocalizationValue(values map[string]string, field string) *asc.NullableString

VersionLocalizationValue returns a pointer to the named value for an optional nullable attribute, or nil when the field is not being written.

func VisibleHelpFlags

func VisibleHelpFlags(fs *flag.FlagSet) []*flag.Flag

VisibleHelpFlags returns the flags that should appear in help output.

func WarnIncludeSensitive added in v1.260731.0

func WarnIncludeSensitive(w io.Writer, includeSensitive bool)

WarnIncludeSensitive writes the plaintext-secret warning when the opt-in is enabled. It is a no-op otherwise so default output stays quiet.

func WithAppStoreVersionCreateConflictDiagnostics

func WithAppStoreVersionCreateConflictDiagnostics(ctx context.Context, client *asc.Client, appID, version, platform string, createErr error) error

WithAppStoreVersionCreateConflictDiagnostics explains an HTTP 409 from POST /v1/appStoreVersions. Apple answers both a reused version string and a platform that already has an unreleased version with "You cannot create a new version of the App in the current state.", so this reads the platform's versions and names the existing version with that string or the unreleased versions, with the command that reuses, renames, or releases each one. It reports current state without claiming which version caused the rejection. Other failures, and a failed diagnostic read, return createErr unchanged.

func WithAppStoreVersionNotFoundDiagnostics

func WithAppStoreVersionNotFoundDiagnostics(ctx context.Context, client *asc.Client, appID, version, platform string, notFound error) error

WithAppStoreVersionNotFoundDiagnostics appends the app's existing App Store versions, newest first, and the command that targets or creates the requested version to a "version not found" error. An empty platform lists every platform. The returned error keeps notFound's classification; when the extra read fails, notFound is returned unchanged.

func WithDiagnostic added in v1.260819.0

func WithDiagnostic(err error, code DiagnosticCode, parameter string) error

WithDiagnostic attaches allowlisted structured metadata to err. Unknown codes are deliberately ignored so arbitrary strings cannot become a telemetry dimension.

func WithPrivateKeyDiagnostic

func WithPrivateKeyDiagnostic(rendered, cause error) error

WithPrivateKeyDiagnostic attaches the --private-key diagnostic that matches cause's private key failure reason. Other errors are returned unchanged.

func WithSelectorFlag

func WithSelectorFlag(err error, flag string) error

WithSelectorFlag names the flag that accepts an explicit ASC ID in an ambiguous stable-selector error, for commands whose selector flag differs from the default for the resource kind. Other errors pass through unchanged.

func WithSpinnerDelayed

func WithSpinnerDelayed(label string, delay time.Duration, fn func() error) (err error)

WithSpinnerDelayed runs fn while rendering a gh-style indeterminate spinner on stderr, but only starts the spinner after delay has elapsed.

This avoids spinner “flicker” for fast operations while still providing feedback for slower operations (e.g., keychain prompts).

func WrapCommandOutputValidation

func WrapCommandOutputValidation(cmd *ffcli.Command, d *Deps)

WrapCommandOutputValidation ensures an --app given on the command line is not blank and shared output flags are valid before command execution, so both fail before side effects. The diagnostic goes to d's stderr.

func WriteAppInfoLocalizationStrings

func WriteAppInfoLocalizationStrings(outputPath string, items []asc.Resource[asc.AppInfoLocalizationAttributes]) ([]asc.LocalizationFileResult, error)

func WriteFileNoSymlinkOverwrite

func WriteFileNoSymlinkOverwrite(path string, reader io.Reader, perm os.FileMode, tempPattern string, backupPattern string) (int64, error)

WriteFileNoSymlinkOverwrite writes reader to path via temp+rename. It refuses to overwrite symlinks and uses a Windows-safe replace when needed.

func WriteProfileFile

func WriteProfileFile(path string, content []byte) error

WriteProfileFile writes provisioning profile data to disk securely.

func WriteStreamToFile

func WriteStreamToFile(path string, reader io.Reader) (int64, error)

WriteStreamToFile writes a reader to a file securely.

func WriteVersionLocalizationStrings

func WriteVersionLocalizationStrings(outputPath string, items []asc.Resource[asc.AppStoreVersionLocalizationAttributes]) ([]asc.LocalizationFileResult, error)

Types

type APIOperation

type APIOperation struct {
	Method string
	Path   string
	// QueryNames is nil until the query parameters are known.
	QueryNames []string
}

APIOperation is what `asc api` parsed from its arguments, kept for the invocation's telemetry event: the method, the request path and the names of the query parameters, never their values. The telemetry event reduces the path to a schema template and the names to schema names before anything leaves the process.

func WithAPIOperationRecord

func WithAPIOperationRecord(ctx context.Context) (context.Context, *APIOperation)

WithAPIOperationRecord returns a context in which RecordAPIOperation and RecordAPIQueryNames fill the returned APIOperation.

type ASCTerritoryValuePair added in v1.260407.0

type ASCTerritoryValuePair struct {
	TerritoryID string
	Value       string
}

func ParseASCTerritoryValueCSV added in v1.260407.0

func ParseASCTerritoryValueCSV(value string) ([]ASCTerritoryValuePair, error)

type AddBuildBetaGroupsOptions

type AddBuildBetaGroupsOptions struct {
	SkipInternal              bool
	SkipInternalWithAllBuilds bool
	Notify                    bool
}

AddBuildBetaGroupsOptions controls how resolved groups are assigned to a build.

type AddBuildBetaGroupsResult

type AddBuildBetaGroupsResult struct {
	AddedGroupIDs                  []string
	SkippedInternalGroups          []ResolvedBetaGroup
	SkippedInternalAllBuildsGroups []ResolvedBetaGroup
	NotificationAction             asc.BuildBetaGroupsNotificationAction
}

AddBuildBetaGroupsResult reports the final add/skipped group sets.

func AddBuildBetaGroups

func AddBuildBetaGroups(ctx context.Context, client buildBetaGroupsMutationClient, buildID string, groups []ResolvedBetaGroup, opts AddBuildBetaGroupsOptions) (*AddBuildBetaGroupsResult, error)

AddBuildBetaGroups applies resolved beta groups to a build, optionally skipping internal groups.

type AmbiguousCandidate

type AmbiguousCandidate struct {
	ID    string
	Label string
	Extra string
}

AmbiguousCandidate is one resource that matched a selector which should have matched exactly one. ID is the value the disambiguating flag accepts; Label and Extra are optional human context (name, platform, state).

func AppCandidates

func AppCandidates(apps []asc.Resource[asc.AppAttributes]) []AmbiguousCandidate

AppCandidates converts apps into ambiguity candidates (ID, name, bundle ID).

func AppInfoAmbiguousCandidates

func AppInfoAmbiguousCandidates(appInfos []asc.AppInfoCandidate) []AmbiguousCandidate

AppInfoAmbiguousCandidates converts app info candidates into ambiguity candidates (ID, state).

func AppStoreVersionCandidates

func AppStoreVersionCandidates(versions []asc.Resource[asc.AppStoreVersionAttributes]) []AmbiguousCandidate

AppStoreVersionCandidates converts App Store versions into ambiguity candidates (ID, "<version> <platform>", state).

func BetaTesterCandidates

func BetaTesterCandidates(testers []asc.Resource[asc.BetaTesterAttributes]) []AmbiguousCandidate

BetaTesterCandidates converts beta testers into ambiguity candidates. The selector already identifies the duplicated email, so only expose the IDs accepted by the disambiguating command instead of repeating personal data.

func BuildCandidate

func BuildCandidate(build asc.Resource[asc.BuildAttributes]) AmbiguousCandidate

BuildCandidate converts one build into an ambiguity candidate.

func BuildCandidates

func BuildCandidates(builds []asc.Resource[asc.BuildAttributes]) []AmbiguousCandidate

BuildCandidates converts builds into ambiguity candidates (ID, build number, uploaded date and processing state).

func ExactSelectorAmbiguousCandidates

func ExactSelectorAmbiguousCandidates(matches []ExactSelectorCandidate) []AmbiguousCandidate

ExactSelectorAmbiguousCandidates converts selector matches into ambiguity candidates (ID, product ID, name).

func LocalizationCandidates

func LocalizationCandidates[T any](items []asc.Resource[T], locale func(T) string) []AmbiguousCandidate

LocalizationCandidates converts resources into ambiguity candidates keyed by ID with the given locale as the label.

type AmbiguousDefaultAppStoreVersionError

type AmbiguousDefaultAppStoreVersionError struct {
	AppID      string
	Source     string
	Candidates []DefaultAppStoreVersion
}

AmbiguousDefaultAppStoreVersionError reports that more than one platform has a candidate default version, so the caller must pass --platform. It unwraps to AmbiguousSelectionError so callers share the standard typed, sanitized candidate-table contract.

func (*AmbiguousDefaultAppStoreVersionError) Error

func (*AmbiguousDefaultAppStoreVersionError) Unwrap

type AmbiguousSelectionError

type AmbiguousSelectionError struct {
	// Kind is the singular resource noun, for example "app" or "beta group".
	Kind string
	// Description says what was matched, already quoted or qualified, for
	// example `"Outslept"` or `version "1.2.3" on platform "IOS"`.
	Description string
	// Flag is the flag that accepts one candidate ID, for example "--app".
	// Leave empty when no single flag disambiguates.
	Flag string
	// Candidates lists the matches in the order they should be shown.
	Candidates []AmbiguousCandidate
	// CandidatesAreSample reports that the candidates prove ambiguity but do
	// not establish the total match count. This keeps early-stopping resolvers
	// from presenting the retained sample as a complete result set.
	CandidatesAreSample bool
	// Hint is an optional final line with additional guidance.
	Hint string
	// DisplayTextLimit bounds each rendered field after terminal sanitization.
	// Zero preserves the historical unbounded rendering. Structured fields
	// always retain their complete values.
	DisplayTextLimit int
}

AmbiguousSelectionError reports that a selector matched several resources. The rendered message names every candidate (bounded by AmbiguousCandidateLimit) with its ID and the flag that disambiguates, so an agent can recover by re-running with one of the listed IDs.

func (*AmbiguousSelectionError) Error

func (e *AmbiguousSelectionError) Error() string

Error renders the header, the bounded candidate table, and the hint.

func (*AmbiguousSelectionError) ValidationFailure

func (e *AmbiguousSelectionError) ValidationFailure() bool

ValidationFailure reports ambiguity as a validation outcome: the request was understood but needs a disambiguating selector, which is not a defect in asc. The message and exit code are unchanged.

type AppInfoLocalizationUpsertPlan added in v1.260816.0

type AppInfoLocalizationUpsertPlan struct {
	AppInfoID      string
	LocalizationID string
	Locale         string
	Attributes     asc.AppInfoLocalizationAttributes
	Create         bool
}

AppInfoLocalizationUpsertPlan describes a resolved app-info localization write. Planning resolves and validates the target before callers perform any mutations.

type AppStoreLocalizationLocale added in v1.260407.0

type AppStoreLocalizationLocale struct {
	Code             string `json:"code"`
	Name             string `json:"name"`
	SupportsMetadata bool   `json:"supportsMetadata"`
}

AppStoreLocalizationLocale describes one known App Store localization locale.

func AppStoreLocalizationCatalog added in v1.260407.0

func AppStoreLocalizationCatalog() []AppStoreLocalizationLocale

AppStoreLocalizationCatalog returns the known App Store localization catalog.

type AppStoreVersionStateFilter

type AppStoreVersionStateFilter struct {
	// AppStoreStates are deprecated appStoreState values.
	AppStoreStates []string
	// AppVersionStates are appVersionState values.
	AppVersionStates []string
}

AppStoreVersionStateFilter selects App Store versions by state across both state attributes. App Store Connect combines filter[appStoreState] and filter[appVersionState] with AND, so each non-empty spelling is sent as its own request and the results are merged.

func LiveAppStoreVersionStateFilter

func LiveAppStoreVersionStateFilter() AppStoreVersionStateFilter

LiveAppStoreVersionStateFilter selects versions that are live on the App Store under either spelling. Callers may append further states to the returned filter; each call returns fresh slices.

type AttributeFlag

type AttributeFlag struct {
	// contains filtered or unexported fields
}

AttributeFlag is a string flag whose trimmed value a create or update command writes to a request field.

func ExplicitStringFlag

func ExplicitStringFlag(target **string, name, usage string) AttributeFlag

ExplicitStringFlag binds a string flag to target, which stays nil unless the flag appears on the command line, even with a blank value.

func OptionalStringFlag

func OptionalStringFlag(target **string, name, usage string) AttributeFlag

OptionalStringFlag binds a string flag to target, which stays nil while the flag is blank or not given.

func RequiredStringFlag

func RequiredStringFlag(target *string, name, usage string) AttributeFlag

RequiredStringFlag binds a string flag that must not be blank to target.

func StringFlag

func StringFlag(target *string, name, usage string) AttributeFlag

StringFlag binds a string flag to target, which is blank while the flag is blank or not given.

type AvailabilityRemoveFromSaleCommandConfig added in v1.260819.0

type AvailabilityRemoveFromSaleCommandConfig struct {
	ClientFactory func() (*asc.Client, error)
	// Deps supplies the streams and timeout.
	Deps *Deps
}

AvailabilityRemoveFromSaleCommandConfig configures the remove-from-sale command.

type AvailabilitySetCommandConfig

type AvailabilitySetCommandConfig struct {
	FlagSetName                      string
	CommandName                      string
	ShortUsage                       string
	ShortHelp                        string
	LongHelp                         string
	ErrorPrefix                      string
	IncludeAvailableInNewTerritories bool
	// Deps supplies the streams and the request timeout. The client is not
	// taken from it: the command resolves credentials without the auth spinner
	// GetASCClient shows.
	Deps *Deps
}

AvailabilitySetCommandConfig configures the availability set command.

type BuildBetaGroupAssignmentPlan

type BuildBetaGroupAssignmentPlan struct {
	GroupsToAdd                    []ResolvedBetaGroup
	SkippedInternalGroups          []ResolvedBetaGroup
	SkippedInternalAllBuildsGroups []ResolvedBetaGroup
}

BuildBetaGroupAssignmentPlan describes the groups that an assignment would send after applying the configured skip rules. It performs no API calls.

func PlanBuildBetaGroupAssignment

func PlanBuildBetaGroupAssignment(groups []ResolvedBetaGroup, opts AddBuildBetaGroupsOptions) BuildBetaGroupAssignmentPlan

PlanBuildBetaGroupAssignment applies assignment filtering without making a mutation or consulting provider state. This is shared by normal execution and the command's dry-run preview so the planned IDs cannot drift from the eventual relationship payload.

func (BuildBetaGroupAssignmentPlan) GroupIDsToAdd

func (p BuildBetaGroupAssignmentPlan) GroupIDsToAdd() []string

GroupIDsToAdd returns the beta group IDs that belong in the relationship request, without exposing the plan's backing slice.

func (BuildBetaGroupAssignmentPlan) IncludesExternalGroup

func (p BuildBetaGroupAssignmentPlan) IncludesExternalGroup() bool

IncludesExternalGroup reports whether the plan contains an external group.

type BuildBetaGroupPreflightOptions

type BuildBetaGroupPreflightOptions struct {
	OperationName string
}

BuildBetaGroupPreflightOptions controls diagnostics for the assignment.

type BuildBetaReviewSubmissionResult added in v1.260425.0

type BuildBetaReviewSubmissionResult struct {
	Submitted    bool
	SubmissionID string
	Message      string
}

BuildBetaReviewSubmissionResult reports the beta app review submission outcome.

func SubmitBuildBetaReviewIfNeeded added in v1.260425.0

func SubmitBuildBetaReviewIfNeeded(ctx context.Context, client buildBetaReviewSubmissionClient, buildID string, groups []ResolvedBetaGroup, addedGroupIDs []string, submit bool, operationName string) (*BuildBetaReviewSubmissionResult, error)

SubmitBuildBetaReviewIfNeeded submits a build for beta app review when requested and when the build was added to at least one external beta group.

type BuildProcessingFailureContext

type BuildProcessingFailureContext struct {
	AppID         string
	BuildID       string
	BundleVersion string
	ShortVersion  string
	Platform      string
}

BuildProcessingFailureContext identifies the artifact behind a build that finished processing in a failure state, so the upload it came from can be matched even when the caller selected the build by ID alone.

type BuildProcessingStateFilterOptions

type BuildProcessingStateFilterOptions struct {
	FlagName          string
	AllowedValuesHelp string
	Aliases           map[string]string
}

BuildProcessingStateFilterOptions customizes state normalization behavior for command-specific flag names/help text and optional aliases.

type BuildUploadWaitSelector

type BuildUploadWaitSelector struct {
	AppID       string
	Version     string
	BuildNumber string
	Platform    string
	Since       *time.Time
}

BuildUploadWaitSelector identifies the build uploads a build wait reports on while no build matching its selector is visible yet. Empty fields do not filter.

type CategoriesSetCommandConfig

type CategoriesSetCommandConfig struct {
	FlagSetName    string
	ShortUsage     string
	ShortHelp      string
	LongHelp       string
	ErrorPrefix    string
	IncludeAppInfo bool
	// Deps supplies the streams, the request timeout and the output. The
	// client is not taken from it: the command resolves credentials without
	// the auth spinner GetASCClient shows.
	Deps *Deps
}

CategoriesSetCommandConfig configures the categories set command.

type ConfirmDeleteCommandConfig

type ConfirmDeleteCommandConfig struct {
	// FlagSetName names the flag set, which parse errors show. It defaults
	// to Name.
	FlagSetName string
	Name        string
	ShortUsage  string
	ShortHelp   string
	LongHelp    string

	IDFlag  string
	IDUsage string
	// IDType is the API resource type named by the ID flag; see
	// IDGetCommandConfig.IDType.
	IDType string
	// RequiredDiagnostic reports a missing ID flag with the required-input
	// diagnostic instead of a plain usage error.
	RequiredDiagnostic bool
	// ConfirmUsage is the --confirm flag usage. It defaults to
	// "Confirm deletion".
	ConfirmUsage string

	// ErrorPrefix wraps the client error. It defaults to the command path in
	// ShortUsage without "asc ".
	ErrorPrefix string
	// DeleteErrorPrefix wraps errors returned by Delete. It defaults to
	// ErrorPrefix followed by ": failed to delete".
	DeleteErrorPrefix string

	// Deps supplies the client, streams and timeout.
	Deps *Deps

	ContextTimeout func(context.Context) (context.Context, context.CancelFunc)
	Delete         func(context.Context, *asc.Client, string) error
	Result         func(string) any
}

ConfirmDeleteCommandConfig configures a standard delete command requiring --id and --confirm.

type DefaultAppStoreVersion

type DefaultAppStoreVersion struct {
	ID            string
	VersionString string
	Platform      string
	State         string
	// Source is DefaultAppStoreVersionSourceEditable or
	// DefaultAppStoreVersionSourceLive.
	Source string
}

DefaultAppStoreVersion describes the version selected when --version is omitted.

func ResolveDefaultAppStoreVersion

func ResolveDefaultAppStoreVersion(ctx context.Context, client *asc.Client, appID, platform string) (DefaultAppStoreVersion, error)

ResolveDefaultAppStoreVersion selects the app's newest editable App Store version, falling back to the newest live version. platform may be empty; when candidates exist on more than one platform the returned error is an *AmbiguousDefaultAppStoreVersionError.

The editable preference is app-wide and is resolved before live versions are considered, so ambiguity is decided within the selected tier rather than across the union of both tiers. An app that is live on iOS and macOS but has a single editable iOS version therefore resolves to that editable version instead of failing: the editable version is the one being worked on, and requiring --platform there would reintroduce the friction this default exists to remove. The selection is never silent — callers announce the resolved version and its platform on stderr through Note.

func (DefaultAppStoreVersion) Note

func (v DefaultAppStoreVersion) Note(overrideFlag string) string

Note renders the stderr diagnostic that tells callers which version was picked and how to override it. overrideFlag is the flag the command reads, for example "--version".

type Deps

type Deps struct {
	Client         func() (*asc.Client, error)
	IO             *IO
	Now            func() time.Time
	Timeout        func(context.Context) (context.Context, context.CancelFunc)
	UploadTimeout  func(context.Context) (context.Context, context.CancelFunc)
	ResolveTimeout func(setting TimeoutSetting, defaultTimeout time.Duration) time.Duration

	After func(time.Duration) <-chan time.Time

	Getwd func() (string, error)

	// LookupEnv reads the environment variables a command takes as input,
	// such as ASC_APP_ID, as os.LookupEnv. Credentials, the profile and the
	// config are still read from the process environment. nil reads as an
	// empty environment, so a test that does not care about the environment
	// need not set it and never sees the process environment.
	LookupEnv func(string) (string, bool)

	HTTPTransport func() http.RoundTripper

	ClientWithTimeout func(time.Duration) (*asc.Client, error)
}

Deps holds what a command takes from the process: its App Store Connect client, its streams, the clock, the request and upload timeouts, and the timeout settings a command reads with a default of its own. After is the timer a command waits on, as time.After. Getwd is the working directory a command reads explicitly, as os.Getwd; relative paths a command passes to the operating system or to filepath.Abs still resolve against the process directory. HTTPTransport is the transport of the clients a command builds for services other than the App Store Connect API. ClientWithTimeout returns an App Store Connect client whose HTTP timeout is the given duration, for commands whose single requests may run longer than the request timeout.

func DefaultDeps

func DefaultDeps() *Deps

DefaultDeps returns the dependencies of a normal run: the shared client factory, the process streams, the system clock and timers, the timeouts from the environment and the config file, the process working directory, and the process HTTP transport.

func (*Deps) Abs

func (d *Deps) Abs(path string) (string, error)

Abs is filepath.Abs with a relative path resolved against d.Getwd instead of the process directory: on Unix, filepath.Abs cleans an absolute path and joins a relative one to the working directory.

func (*Deps) AmbiguousUsageError

func (d *Deps) AmbiguousUsageError(err error) error

AmbiguousUsageError prints an ambiguity error to d's stderr line by line and returns a usage-class error (exit code 2). UsageError cannot be used for this because its terminal sanitizer flattens the candidate table onto one line.

func (*Deps) AmbiguousUsageErrorWithKind

func (d *Deps) AmbiguousUsageErrorWithKind(err error, kind UsageErrorKind) error

AmbiguousUsageErrorWithKind prints an ambiguity error to d's stderr line by line and returns a usage-class error (exit code 2) with the requested telemetry classification. AmbiguousUsageError intentionally remains UsageErrorOther for callers whose ambiguity is not a missing or invalid flag.

func (*Deps) AppIDFlagValue

func (d *Deps) AppIDFlagValue(value string) (string, error)

AppIDFlagValue normalizes the value of an --app flag that keeps a plain string default (for example one seeded from ASC_APP_ID) and so cannot be bound with BindResourceIDFlag without changing its help text. It accepts an apps self-link and reports a link of another type as a concise usage error with the same message as a flag-parse failure, written to d's stderr.

func (*Deps) ApplyTerritoryAvailabilityUpdate

func (d *Deps) ApplyTerritoryAvailabilityUpdate(ctx context.Context, client *asc.Client, request TerritoryAvailabilityUpdateRequest) (*asc.AppAvailabilityV2Response, int, error)

ApplyTerritoryAvailabilityUpdate applies request to an app's existing availability record and returns Apple's response together with the number of territories whose availability actually changed (0 when every requested territory already matched). It is the same code path "asc pricing availability edit" runs, exported so a create-style command can route --if-exists update to it instead of duplicating the update logic. Progress lines go to d's stderr.

func (*Deps) AvailabilityTimeout

func (d *Deps) AvailabilityTimeout(ctx context.Context, allTerritories bool) (context.Context, context.CancelFunc)

AvailabilityTimeout returns the request context for availability updates on d: all-territories updates fan out one PATCH per territory, so they get the longer bulk timeout.

func (*Deps) BindOutputFlags

func (d *Deps) BindOutputFlags(fs *flag.FlagSet) OutputFlags

BindOutputFlags registers --output and --pretty. Unless ASC_DEFAULT_OUTPUT or a CI environment decides otherwise, --output defaults to table when d's stdout is a terminal and to json when it is not.

func (*Deps) BindTargetSubscriptionPlanTypeFlag

func (d *Deps) BindTargetSubscriptionPlanTypeFlag(fs *flag.FlagSet) func() (asc.SubscriptionPlanType, error)

BindTargetSubscriptionPlanTypeFlag registers the optional flag shared by the subscription offer create commands. The returned function validates the value, writing its "Error:" line to d's stderr, and yields an empty plan type only when the flag was not provided.

func (*Deps) Bold

func (d *Deps) Bold(s string) string

Bold returns s wrapped in ANSI bold codes when d's stderr is a terminal.

func (*Deps) CreateLibraryPlacement

func (d *Deps) CreateLibraryPlacement(ctx context.Context, client *asc.Client, resource, localizationID, mediaRelationship, mediaID, placementType, placementGroup string) (id, state string, err error)

CreateLibraryPlacement assigns uploaded library media to one localization, with the request deadline from d.Timeout. mediaRelationship is "image" or "video".

func (*Deps) CreativePlacementsCommand

func (d *Deps) CreativePlacementsCommand(resource, prefix, label string) *ffcli.Command

CreativePlacementsCommand manages reusable library placements for a localization, with every subcommand built on d.

func (*Deps) DecompressGzipFile

func (d *Deps) DecompressGzipFile(sourcePath, destPath string) (int64, error)

DecompressGzipFile inflates a gzip file to the destination path, with relative paths resolved against d's working directory.

func (*Deps) DefaultOutputFormat

func (d *Deps) DefaultOutputFormat() string

DefaultOutputFormat returns the default output format for CLI commands. It checks ASC_DEFAULT_OUTPUT first and reports an invalid value to d's stderr. When unset, an interactive stdout defaults to table output while CI and non-interactive contexts default to JSON. Valid ASC_DEFAULT_OUTPUT values are "json", "table", "markdown", and "md".

func (*Deps) DefaultUsageFunc

func (d *Deps) DefaultUsageFunc(c *ffcli.Command) string

DefaultUsageFunc is DefaultUsageFunc with bold headings decided from d's stderr, where help is written.

func (*Deps) DownloadTimeout

func (d *Deps) DownloadTimeout(ctx context.Context) (context.Context, context.CancelFunc)

DownloadTimeout bounds a streamed download, including the body copy. Client and request timeouts also cover that copy, so the short request budget aborts a large report mid-transfer. Downloads use d's upload budget.

func (*Deps) ExplainReviewSubmissionNotCancellable

func (d *Deps) ExplainReviewSubmissionNotCancellable(ctx context.Context, client *asc.Client, submissionID string, cancelErr error) error

ExplainReviewSubmissionNotCancellable reads a review submission's current state after App Store Connect refused to cancel it and returns an error that explains the state and the next step. It returns cancelErr unchanged when cancelErr is not that refusal, or when the state cannot be read, so a failed follow-up read never hides the original error. The read's deadline comes from d.Timeout.

func (*Deps) FinalizeLocalizationUploadResult

func (d *Deps) FinalizeLocalizationUploadResult(result *asc.LocalizationUploadResult, command string)

FinalizeLocalizationUploadResult is FinalizeLocalizationUploadResult with the retry artifact written relative to d's working directory and stamped with d's clock.

func (*Deps) FindPreReleaseVersionIDs

func (d *Deps) FindPreReleaseVersionIDs(ctx context.Context, client *asc.Client, appID, version, platform string) ([]string, error)

FindPreReleaseVersionIDs returns the exact-matching pre-release version IDs for the provided app/version/platform filters. App Store Connect treats "1.2" and "1.2.0" as the same version, so when the requested format matches nothing the equivalent format is tried before reporting no match, with a note on d's stderr.

func (*Deps) FindPreReleaseVersionIDsWithMaxPages

func (d *Deps) FindPreReleaseVersionIDsWithMaxPages(ctx context.Context, client *asc.Client, appID, version, platform string, maxPages int) ([]string, error)

FindPreReleaseVersionIDsWithMaxPages is the bounded variant used by selectors that must keep their complete lookup within a finite pagination budget. The unbounded FindPreReleaseVersionIDs remains available for callers whose existing pagination semantics must not change.

func (*Deps) Getenv

func (d *Deps) Getenv(name string) string

Getenv is os.Getenv through d.LookupEnv.

func (*Deps) MediaUploadTimeout

func (d *Deps) MediaUploadTimeout(ctx context.Context, bytes int64) (context.Context, context.CancelFunc)

MediaUploadTimeout bounds one media file's upload and processing wait by ASC_UPLOAD_TIMEOUT, or by MediaUploadTimeoutForWork when it is unset.

func (*Deps) MissingRelationshipTypeUsageError

func (d *Deps) MissingRelationshipTypeUsageError(values []string) error

MissingRelationshipTypeUsageError prints the missing --type diagnostic with every accepted relationship type to d's stderr and returns the shared missing-required usage error so the command exits with usage semantics.

func (*Deps) NewFlagSet

func (d *Deps) NewFlagSet(name string, errorHandling flag.ErrorHandling) *flag.FlagSet

NewFlagSet returns a flag set that writes usage and parse errors to d's stderr.

func (*Deps) NormalizeBuildProcessingStateFilter

func (d *Deps) NormalizeBuildProcessingStateFilter(raw string, options BuildProcessingStateFilterOptions) ([]string, error)

NormalizeBuildProcessingStateFilter parses and validates CSV processing-state filters (including "all"), deduplicates values, and applies optional aliases. An invalid value's "Error:" line goes to d's stderr.

func (*Deps) NormalizeLatestBuildSelectionOptions

func (d *Deps) NormalizeLatestBuildSelectionOptions(appID, version, platform, processingState string, excludeExpired bool) (LatestBuildSelectionOptions, error)

NormalizeLatestBuildSelectionOptions validates and normalizes the common version/platform filters shared by latest-build selection workflows. An invalid value's "Error:" line goes to d's stderr.

func (*Deps) OSPath

func (d *Deps) OSPath(path string) string

OSPath is the path to hand to the operating system for path, a path given relative to d's working directory: path itself when filepath.Abs resolves it to the same place as d.Abs, so the operating system sees and reports the path as given, and d.Abs(path) otherwise.

func (*Deps) OrderLibraryPlacements

func (d *Deps) OrderLibraryPlacements(ctx context.Context, client *asc.Client, resource, localizationID, placementGroup string, placementIDs []string) (string, error)

OrderLibraryPlacements submits one ordering request for a localization's placement group and returns the request ID, with the request deadline from d.Timeout.

func (*Deps) PPPTerritorySelection

func (d *Deps) PPPTerritorySelection(value *OnceCSVValue) ([]string, error)

PPPTerritorySelection validates an optional, explicitly supplied mutation scope, writing an invalid value's "Error:" line to d's stderr.

func (*Deps) PaginateWithSpinner

func (d *Deps) PaginateWithSpinner(ctx context.Context, fetch FetchFunc, next asc.PaginateFunc) (asc.PaginatedResponse, error)

PaginateWithSpinner fetches all pages with a spinner on d's stderr, shown only when d's stdout and stderr are terminals. It wraps both the initial fetch and the pagination loop so the spinner is visible even for single-page results.

func (*Deps) ParseIfExistsMode

func (d *Deps) ParseIfExistsMode(raw string, supported ...IfExistsMode) (IfExistsMode, error)

ParseIfExistsMode validates the raw --if-exists value against the modes the command supports. It returns a usage-class error (exit code 2) before any HTTP request so an unsupported value is never silently ignored, and writes its "Error:" line to d's stderr.

BindIfExistsFlag defaults the flag to fail, so an empty or all-whitespace raw value can only come from an explicitly supplied --if-exists "" and is rejected rather than silently read as fail.

func (*Deps) ParseOptionalIfExistsMode

func (d *Deps) ParseOptionalIfExistsMode(raw string, supported ...IfExistsMode) (IfExistsMode, error)

ParseOptionalIfExistsMode is ParseIfExistsMode for a value that may legitimately be absent: a PushExecutionOptions-style field an in-process caller left unset, or a mode read back from an artifact written before --if-exists existed. An absent value means fail, the historical behavior. A non-empty unsupported value is still a usage error.

Do not use this for a bound --if-exists flag value. BindIfExistsFlag defaults the flag to fail, so an empty value there was supplied explicitly and ParseIfExistsMode rejects it.

func (*Deps) ParsePriceRounding

func (d *Deps) ParsePriceRounding(value string) (PriceRounding, error)

ParsePriceRounding returns the --round mode named by value, or a usage error with its "Error:" line on d's stderr.

func (*Deps) PlanAppInfoLocalizationUpsert

func (d *Deps) PlanAppInfoLocalizationUpsert(
	ctx context.Context,
	client *asc.Client,
	appID string,
	appInfoID string,
	locale string,
	values map[string]string,
) (*AppInfoLocalizationUpsertPlan, error)

PlanAppInfoLocalizationUpsert resolves one locale and validates whether it can be created or updated without performing a mutation. The app info auto-selection notice goes to d's stderr.

func (*Deps) PreflightBuildBetaGroupAssignment

func (d *Deps) PreflightBuildBetaGroupAssignment(
	ctx context.Context,
	client buildBetaGroupPreflightClient,
	buildID string,
	plan BuildBetaGroupAssignmentPlan,
	opts BuildBetaGroupPreflightOptions,
) error

PreflightBuildBetaGroupAssignment checks the provider state required for a relationship assignment. A normal assignment fails closed when the current state cannot prove that the relationship is acceptable; this keeps an unavailable or incomplete read from turning into an avoidable POST. The pure state checks are shared with the diagnostic wording used by callers. The "Error:" lines go to d's stderr.

func (*Deps) PreflightReviewScreenshot

func (d *Deps) PreflightReviewScreenshot(path string, file io.ReaderAt, size int64) error

PreflightReviewScreenshot checks the bytes of an in-app purchase or subscription App Review screenshot that are about to be uploaded. A format problem App Store Connect would reject at delivery is returned as an error before any request. Documented but unconfirmed constraints (size and alpha) and a payload that does not fully decode are printed to d's stderr as warnings.

func (*Deps) PrintInvalidRelationshipTypeError

func (d *Deps) PrintInvalidRelationshipTypeError(value string, values []string)

PrintInvalidRelationshipTypeError prints the rejected --type value alongside every accepted relationship type to d's stderr. Callers return their own usage error so each links command keeps its existing error classification.

func (*Deps) PrintOutput

func (d *Deps) PrintOutput(data any, format string, pretty bool) error

PrintOutput writes data to d's stdout in the given format, and the notice that more pages exist to d's stderr.

func (*Deps) PrintOutputRows

func (d *Deps) PrintOutputRows(data any, format string, pretty bool, headers []string, rows [][]string) error

PrintOutputRows prints data to d's stdout as JSON, or as one table of headers and rows.

func (*Deps) PrintOutputWithRenderers

func (d *Deps) PrintOutputWithRenderers(data any, format string, pretty bool, tableRenderer, markdownRenderer func() error) error

PrintOutputWithRenderers writes data as JSON to d's stdout, or calls the table or markdown renderer for those formats, then writes the more-pages notice to d's stderr. The renderers must write to d.IO.Out themselves.

func (*Deps) PrintResolvedPrices

func (d *Deps) PrintResolvedPrices(result *ResolvedPricesResult, format string, pretty bool) error

PrintResolvedPrices renders resolved price rows on d's stdout and stderr without registering global raw renderers.

func (*Deps) PrintStreamPage

func (d *Deps) PrintStreamPage(data any) error

PrintStreamPage writes a single page of data as a JSON line to d's stdout. Used with --stream --paginate to emit results page-by-page as NDJSON instead of buffering all pages in memory.

func (*Deps) ProgressEnabled

func (d *Deps) ProgressEnabled() bool

ProgressEnabled reports whether it's safe/appropriate to emit progress messages. Progress must be stderr-only and must not appear when d's stderr is non-interactive.

func (*Deps) ReadJSONFilePayload

func (d *Deps) ReadJSONFilePayload(path string) (json.RawMessage, error)

ReadJSONFilePayload loads a JSON object from a file path ("-" for d's stdin) for commands that accept raw payload documents.

func (*Deps) ReadJSONFilePayloadKind

func (d *Deps) ReadJSONFilePayloadKind(path string, kind JSONPayloadKind) (json.RawMessage, error)

ReadJSONFilePayloadKind loads a JSON payload from a file path ("-" for d's stdin, refused when that stdin is a terminal) and validates the requested top-level JSON shape.

func (*Deps) RecoverBoolFlagTailArgs

func (d *Deps) RecoverBoolFlagTailArgs(original *flag.FlagSet, args []string, currentValue *bool) error

RecoverBoolFlagTailArgs reparses leftover args when the standard flag parser stops after a space-separated boolean value for a bool flag. This preserves support for `--flag`, `--flag=true`, and `--flag=false` while also recovering `--flag true` / `--flag false` for commands that don't accept positional args. The "Error:" line goes to d's stderr.

func (*Deps) RejectNextFlagConflicts

func (d *Deps) RejectNextFlagConflicts(fs *flag.FlagSet, next, command string, names ...string) error

RejectNextFlagConflicts rejects explicitly provided query flags when --next supplies the complete continuation request, including its query string. The "Error:" line goes to d's stderr.

func (*Deps) RejectOutputFormatAsPath

func (d *Deps) RejectOutputFormatAsPath(path, formatFlag string) error

RejectOutputFormatAsPath reports a usage error, with its "Error:" line on d's stderr, when a command whose --output flag takes a path is given an output format name there. formatFlag is the command's flag that chooses json, table or markdown, or "" when it has none.

func (*Deps) RenderLocalizationUploadResult

func (d *Deps) RenderLocalizationUploadResult(result *asc.LocalizationUploadResult, markdown bool) error

RenderLocalizationUploadResult renders both the batch summary and per-locale details on d's stdout so interactive output includes retry artifact information.

func (*Deps) RenderSection

func (d *Deps) RenderSection(title string, headers []string, rows [][]string, markdown bool)

RenderSection renders a titled section as markdown or table output on d's stdout, with the title bold when d's stderr is a terminal.

func (*Deps) RequireAppForStableSelector

func (d *Deps) RequireAppForStableSelector(appID, selector, flagName string) error

RequireAppForStableSelector returns a usage error, with its "Error:" line on d's stderr, when a non-numeric selector needs app context.

func (*Deps) RequireConfirm

func (d *Deps) RequireConfirm(confirm bool) error

RequireConfirm is RequireConfirm with the "Error:" line written to d's stderr.

func (*Deps) RequireConfirmUnlessDryRun

func (d *Deps) RequireConfirmUnlessDryRun(dryRun, confirm bool) error

RequireConfirmUnlessDryRun enforces the apply decision for commands that turn file input into App Store Connect mutations: the caller must either preview the plan with --dry-run or accept the mutation with --confirm. The "Error:" line goes to d's stderr.

When both flags are set, --dry-run wins and nothing is mutated. That matches the existing convention in `asc release stage`, `asc review submit`, and `asc subscriptions pricing equalize`, so contradictory input resolves to the safe side in every command instead of being rejected in some and honored in others.

func (*Deps) RequiredFlag

func (d *Deps) RequiredFlag(name string) error

RequiredFlag is RequiredFlag with the "Error:" line written to d's stderr.

func (*Deps) ResolveAndAnnounceDefaultAppStoreVersion

func (d *Deps) ResolveAndAnnounceDefaultAppStoreVersion(ctx context.Context, client *asc.Client, appID, platform, overrideFlag string) (DefaultAppStoreVersion, error)

ResolveAndAnnounceDefaultAppStoreVersion resolves the default App Store version for commands whose --version flag was omitted, prints the selection note to d's stderr, and maps platform ambiguity to an already-printed usage error (exit 2 without the full help page). overrideFlag is the flag name shown in the note.

func (*Deps) ResolveAppID

func (d *Deps) ResolveAppID(appID string) string

ResolveAppID is ResolveAppID with ASC_APP_ID read through d.LookupEnv.

func (*Deps) ResolveAppInfoID

func (d *Deps) ResolveAppInfoID(ctx context.Context, client *asc.Client, appID, appInfoID string) (string, error)

ResolveAppInfoID resolves the app info ID, optionally using a provided override supplied through --app-info. The auto-selection notice goes to d's stderr.

func (*Deps) ResolveAppInfoIDWithFlag

func (d *Deps) ResolveAppInfoIDWithFlag(ctx context.Context, client *asc.Client, appID, appInfoID, appInfoFlag string) (string, error)

ResolveAppInfoIDWithFlag resolves the app info ID, optionally using a provided override. appInfoFlag names the command's override flag so an ambiguity error can tell the caller which flag accepts one candidate ID. The auto-selection notice goes to d's stderr.

func (*Deps) ResolveFlagValueIndirection

func (d *Deps) ResolveFlagValueIndirection(flagName, value string) (string, error)

ResolveFlagValueIndirection expands the value-indirection prefixes shared by every value-taking flag: `@env:NAME` resolves to that environment variable, read through d, `@file:PATH` resolves to that file's contents with one trailing line ending removed, and a leading `@@` escapes a literal `@`. Any other value, including values that merely start with `@`, is returned unchanged. flagName is the bare flag name used in diagnostics.

func (*Deps) ResolveIAPTiers

func (d *Deps) ResolveIAPTiers(ctx context.Context, client *asc.Client, iapID, territory string, refresh bool) ([]TierEntry, error)

ResolveIAPTiers resolves in-app purchase price point tiers for an IAP and territory, with the cache warning written to d's stderr.

func (*Deps) ResolveLatestBuild

func (d *Deps) ResolveLatestBuild(ctx context.Context, client *asc.Client, opts LatestBuildSelectionOptions, allowEmpty bool) (*asc.BuildResponse, error)

ResolveLatestBuild finds the latest processed build matching the provided app/version/platform filters. When allowEmpty is true, nil is returned when no matching build exists. Its notes and "Error:" lines go to d's stderr.

func (*Deps) ResolveNextBuildNumber

func (d *Deps) ResolveNextBuildNumber(ctx context.Context, client *asc.Client, opts NextBuildNumberOptions) (*asc.BuildsNextBuildNumberResult, error)

ResolveNextBuildNumber compares the highest observed processed build and in-flight build upload numbers, then returns the next safe build number. Its notes, warnings and "Error:" lines go to d's stderr.

func (*Deps) ResolveOwnedAppInfoID

func (d *Deps) ResolveOwnedAppInfoID(ctx context.Context, client *asc.Client, appID, appInfoID string) (string, error)

ResolveOwnedAppInfoID resolves the app info ID and verifies that an explicit override belongs to the requested app. The auto-selection notice goes to d's stderr.

func (*Deps) ResolveSubscriptionTiers

func (d *Deps) ResolveSubscriptionTiers(ctx context.Context, client *asc.Client, subscriptionID, territory string, refresh bool) ([]TierEntry, error)

ResolveSubscriptionTiers resolves subscription price point tiers for a subscription and territory, with the cache warning written to d's stderr.

func (*Deps) ResolveTiers

func (d *Deps) ResolveTiers(ctx context.Context, client *asc.Client, appID, territory string, refresh bool) ([]TierEntry, error)

ResolveTiers fetches all price points for a territory, sorts by customerPrice ascending, and assigns tier numbers starting at 1. Free (0.00) price points are excluded. The cache warning goes to d's stderr.

func (*Deps) ResolveVendorNumber

func (d *Deps) ResolveVendorNumber(value string) string

ResolveVendorNumber resolves the vendor number for reports: value, then ASC_VENDOR_NUMBER or ASC_ANALYTICS_VENDOR_NUMBER read through d, then the config file.

func (*Deps) ResolvedTimeout

func (d *Deps) ResolvedTimeout(ctx context.Context, defaultTimeout time.Duration) (context.Context, context.CancelFunc)

ResolvedTimeout is ContextWithResolvedTimeout on d.

func (*Deps) ResolvedUploadTimeout

func (d *Deps) ResolvedUploadTimeout(ctx context.Context, defaultTimeout time.Duration) (context.Context, context.CancelFunc)

ResolvedUploadTimeout returns a context bounded by ASC_UPLOAD_TIMEOUT when configured, or by defaultTimeout otherwise.

func (*Deps) ReviewScreenshotUsageError

func (d *Deps) ReviewScreenshotUsageError(parameter, message string) error

ReviewScreenshotUsageError reports a review screenshot rejected before any request. It prints message as one "Error:" line on d's stderr and returns a usage error (exit 2) that does not wrap flag.ErrHelp, so the command's full usage page does not follow and bury the one actionable line. parameter names the flag that supplied the screenshot for diagnostics. Commands under a re-parented tree pass message through RewriteUsageMessage first.

func (*Deps) SpinnerEnabled

func (d *Deps) SpinnerEnabled() bool

SpinnerEnabled is SpinnerEnabled decided from d's stdout and stderr.

func (*Deps) UpdateFlagRequired

func (d *Deps) UpdateFlagRequired(fs *flag.FlagSet, updateFlags ...any) error

UpdateFlagRequired reports an update command run without any of its update flags. It prints "Error: at least one update flag is required (--a, --b)" to d's stderr and returns MissingRequiredUsageError.

updateFlags are the variables the command's flags in fs are bound to (the pointers fs.String and friends return, or the flag.Value passed to fs.Var), the same ones the command checks. The message names their flags in the order given, so it always matches the flags the command has. A variable that no flag in fs is bound to is a programming error and panics, as redefining a flag does in the flag package.

func (*Deps) UploadPrevalidatedVersionLocalizationsWithWarnings

func (d *Deps) UploadPrevalidatedVersionLocalizationsWithWarnings(ctx context.Context, client versionLocalizationClient, versionID string, valuesByLocale map[string]map[string]string, dryRun bool, submitOpts SubmitReadinessOptions) ([]asc.LocalizationUploadLocaleResult, []SubmitReadinessCreateWarning, error)

UploadPrevalidatedVersionLocalizationsWithWarnings uploads version localizations after the caller has already validated the input value set, with the whatsNew retry warning written to d's stderr.

func (*Deps) UploadVersionLocalizations

func (d *Deps) UploadVersionLocalizations(ctx context.Context, client versionLocalizationClient, versionID string, valuesByLocale map[string]map[string]string, dryRun bool) ([]asc.LocalizationUploadLocaleResult, error)

UploadVersionLocalizations is UploadVersionLocalizationsWithWarnings without the submit-readiness warnings, with the whatsNew retry warning written to d's stderr.

func (*Deps) UploadVersionLocalizationsWithWarnings

func (d *Deps) UploadVersionLocalizationsWithWarnings(ctx context.Context, client versionLocalizationClient, versionID string, valuesByLocale map[string]map[string]string, dryRun bool, submitOpts SubmitReadinessOptions) ([]asc.LocalizationUploadLocaleResult, []SubmitReadinessCreateWarning, error)

UploadVersionLocalizationsWithWarnings validates valuesByLocale and uploads the version localizations, returning the per-locale results and the submit-readiness create warnings. The whatsNew retry warning goes to d's stderr.

func (*Deps) UsageError

func (d *Deps) UsageError(message string) error

UsageError is UsageError with the "Error:" line written to d's stderr.

func (*Deps) UsageErrorCtx

func (d *Deps) UsageErrorCtx(ctx context.Context, message string) error

UsageErrorCtx is UsageError with ctx's command-path rewrites applied to the message, with its "Error:" line written to d's stderr. Commands under a re-parented tree should prefer it so the printed diagnostic names the command path the operator invoked.

func (*Deps) UsageErrorf

func (d *Deps) UsageErrorf(format string, args ...any) error

UsageErrorf is UsageErrorf with the "Error:" line written to d's stderr.

func (*Deps) UsageErrorfCtx

func (d *Deps) UsageErrorfCtx(ctx context.Context, format string, args ...any) error

UsageErrorfCtx formats and returns a usage-class validation error with ctx's command-path rewrites applied, writing its "Error:" line to d's stderr.

func (*Deps) ValidateCertificateCreateMerchantID

func (d *Deps) ValidateCertificateCreateMerchantID(certificateType, merchantID string) error

ValidateCertificateCreateMerchantID enforces the merchantId relationship rules for POST /v1/certificates: the Apple Pay types require it, every other type must not send it. Callers must run this before side effects such as writing a private key or CSR. The "Error:" line goes to d's stderr.

func (*Deps) ValidateCertificateCreateType

func (d *Deps) ValidateCertificateCreateType(flagName, value string) (string, error)

ValidateCertificateCreateType returns the canonical certificate type for value, or a usage-class error, with its "Error:" line on d's stderr, when the value is not a CertificateType.

func (*Deps) ValidatePaginationFlags

func (d *Deps) ValidatePaginationFlags(ctx context.Context, fs *flag.FlagSet, command string, limitMax int, nextConflicts ...string) error

ValidatePaginationFlags reports the first --limit or --next mistake of a list command on d's stderr, in the order every list command checks them: a --limit outside 1..limitMax (0 leaves it unset), a --next value that is not an App Store Connect URL, then --limit or a flag in nextConflicts given together with --next, which is requested verbatim. Each message starts with command, the command path without "asc ", after the command-path rewrites carried by ctx. Run it before the command's required-flag and filter checks.

func (*Deps) VisibleUsageFunc

func (d *Deps) VisibleUsageFunc(c *ffcli.Command) string

VisibleUsageFunc renders command help while omitting deprecated and removed commands from nested subcommand listings, with bold headings decided from d's stderr. Root-level deprecated commands are already hidden elsewhere; this keeps nested canonical help focused on current surfaces.

func (*Deps) WaitForBuildByNumberOrUploadFailure

func (d *Deps) WaitForBuildByNumberOrUploadFailure(ctx context.Context, client *asc.Client, appID, uploadID, version, buildNumber, platform string, pollInterval time.Duration) (*asc.BuildResponse, error)

WaitForBuildByNumberOrUploadFailure waits for a build matching version/build number to appear while also watching the originating build upload for early failure states. This prevents long hangs when App Store Connect rejects the uploaded artifact before a build record is created. The equivalent-version note goes to d's stderr.

func (*Deps) WaitForBuildProcessingWithDetails

func (d *Deps) WaitForBuildProcessingWithDetails(ctx context.Context, client *asc.Client, appID, buildID string, pollInterval time.Duration) (*asc.BuildResponse, error)

WaitForBuildProcessingWithDetails waits for a build to finish processing like asc.Client.WaitForBuildProcessing, with its transient-error notices on d's stderr, and appends the App Store Connect processing details of the originating upload when the build ends FAILED or INVALID. appID may be empty; it is then resolved from the build. The state error is returned unchanged when no details can be resolved.

func (*Deps) WarnDeprecatedAppInfoFields

func (d *Deps) WarnDeprecatedAppInfoFields(fields []string, nextURL string)

WarnDeprecatedAppInfoFields warns on d's stderr only for the legacy AppInfo selector. AgeRatingDeclaration.kidsAgeBand is a separate, supported attribute.

func (*Deps) WithSpinner

func (d *Deps) WithSpinner(label string, fn func() error) error

WithSpinner runs fn while rendering an indeterminate spinner on d's stderr, shown only when d's stdout and stderr are terminals.

func (*Deps) WithSpinnerDelayed

func (d *Deps) WithSpinnerDelayed(label string, delay time.Duration, fn func() error) error

WithSpinnerDelayed is WithSpinnerDelayed with the spinner on d's stderr, shown only when d's stdout and stderr are terminals, after d.After(delay).

func (*Deps) WriteStreamToFile

func (d *Deps) WriteStreamToFile(path string, reader io.Reader) (int64, error)

WriteStreamToFile is WriteStreamToFile with a relative path resolved against d's working directory.

type Diagnostic added in v1.260819.0

type Diagnostic struct {
	Code      DiagnosticCode
	Parameter string
}

Diagnostic carries structured failure metadata without changing the error's user-facing message, classification, cause chain, or exit-code behavior.

func DiagnosticFromError added in v1.260819.0

func DiagnosticFromError(err error) (Diagnostic, bool)

DiagnosticFromError returns the outermost allowlisted diagnostic annotation in err's chain.

type DiagnosticCode added in v1.260819.0

type DiagnosticCode string

DiagnosticCode is a privacy-safe, low-cardinality reason for a command failure. Codes describe the failure independently from the rendered error message; pair them with Parameter when the failure concerns a public flag.

const (
	DiagnosticRequiredInputMissing    DiagnosticCode = "required_input_missing"
	DiagnosticInvalidInput            DiagnosticCode = "invalid_input"
	DiagnosticConflictingInput        DiagnosticCode = "conflicting_input"
	DiagnosticFileNotFound            DiagnosticCode = "file_not_found"
	DiagnosticFilePermissionDenied    DiagnosticCode = "file_permission_denied"
	DiagnosticFilePermissionsInsecure DiagnosticCode = "file_permissions_insecure"
	DiagnosticFileInvalidFormat       DiagnosticCode = "file_invalid_format"
	DiagnosticKeyAlgorithmUnsupported DiagnosticCode = "key_algorithm_unsupported"
	DiagnosticAuthenticationRejected  DiagnosticCode = "authentication_rejected"
	DiagnosticResourceNotFound        DiagnosticCode = "resource_not_found"
	DiagnosticResourceConflict        DiagnosticCode = "resource_conflict"
	DiagnosticStateNotReady           DiagnosticCode = "state_not_ready"
	DiagnosticDSYMNotReady            DiagnosticCode = "dsym_not_ready"
	DiagnosticDependencyFailed        DiagnosticCode = "dependency_failed"
	DiagnosticRequestFailed           DiagnosticCode = "request_failed"
	DiagnosticInternalError           DiagnosticCode = "internal_error"
)

func LocalFileDiagnostic

func LocalFileDiagnostic(err error, contentCode DiagnosticCode) (code DiagnosticCode, ok bool)

LocalFileDiagnostic reports the diagnostic for a failure involving a local file. A missing or unreadable file maps to file_not_found or file_permission_denied. Any other filesystem failure, such as EIO, says nothing about the file, so ok is false. Any other error is a problem with the file's contents and maps to contentCode; an empty contentCode leaves such errors unclassified.

type ExactSelectorCandidate added in v1.260404.0

type ExactSelectorCandidate struct {
	ID        string
	ProductID string
	Name      string
}

ExactSelectorCandidate is a resource that can be matched by ASC ID, product ID, or current name.

func ResolveExactSelectorCandidate added in v1.260404.0

func ResolveExactSelectorCandidate(selector, resourceName string, candidates []ExactSelectorCandidate) (ExactSelectorCandidate, error)

ResolveExactSelectorCandidate resolves a unique candidate by exact product ID first, then exact current name.

type FetchFunc

type FetchFunc func(ctx context.Context) (asc.PaginatedResponse, error)

FetchFunc fetches the first page of a paginated resource.

type HintedError

type HintedError struct {
	Err  error
	Hint string
}

HintedError carries a next step that the root error renderer prints on its own line after the message.

func (*HintedError) Error

func (e *HintedError) Error() string

func (*HintedError) Unwrap

func (e *HintedError) Unwrap() error

type IDGetCommandConfig

type IDGetCommandConfig struct {
	// FlagSetName names the flag set, which parse errors show. It defaults
	// to Name.
	FlagSetName string
	Name        string
	ShortUsage  string
	ShortHelp   string
	LongHelp    string

	IDFlag  string
	IDUsage string
	// IDType is the API resource type named by the ID flag. When set, the flag
	// also accepts that resource's self-link and rejects links of other types.
	IDType string
	// ResolveApp reads the ID flag through ResolveAppID, which falls back to
	// ASC_APP_ID and the config file; a missing app is reported as
	// "--<flag> is required (or set ASC_APP_ID)".
	ResolveApp bool
	// RequiredDiagnostic reports a missing ID flag with the required-input
	// diagnostic instead of a plain usage error.
	RequiredDiagnostic bool

	// ErrorPrefix wraps the client error. It defaults to the command path in
	// ShortUsage without "asc ".
	ErrorPrefix string
	// FetchErrorPrefix wraps errors returned by Fetch. It defaults to
	// ErrorPrefix followed by ": failed to fetch".
	FetchErrorPrefix string

	// Flags registers command-specific flags and returns their validation,
	// which runs after the ID check. The returned function may be nil.
	Flags func(*flag.FlagSet) func() error

	// Deps supplies the client, streams and timeout.
	Deps *Deps

	ContextTimeout func(context.Context) (context.Context, context.CancelFunc)
	Fetch          func(context.Context, *asc.Client, string) (any, error)
}

IDGetCommandConfig configures a standard "get by ID" command.

type IO

type IO struct {
	In        io.Reader
	Out       io.Writer
	ErrOut    io.Writer
	StdinTTY  bool
	StdoutTTY bool
	StderrTTY bool
}

IO holds the streams a command reads and writes, and whether its stdin, stdout and stderr are terminals. When In is the process stdin, whether it is a terminal is checked again on the stdin in use when it is read.

func (*IO) ChildStderr

func (s *IO) ChildStderr() io.Writer

ChildStderr returns the stream a child process writes its stderr to: the process stderr file itself when s.ErrOut writes to it, so a terminal stays a terminal for the commands the child runs, and s.ErrOut otherwise, which then receives the child's output through a pipe.

type IPABundleInfo

type IPABundleInfo struct {
	BundleID    string
	Version     string
	BuildNumber string
	Platform    asc.Platform
}

func ExtractBundleInfoFromIPA

func ExtractBundleInfoFromIPA(ipaPath string) (IPABundleInfo, error)

ExtractBundleInfoFromIPA reads the top-level app's bundle identifier and version metadata from an IPA.

func ExtractBundleInfoFromIPAFile added in v1.260819.0

func ExtractBundleInfoFromIPAFile(file *os.File) (IPABundleInfo, error)

ExtractBundleInfoFromIPAFile reads top-level app metadata from an opened IPA.

type IfExistsMode

type IfExistsMode string

IfExistsMode selects what a create-style command does when App Store Connect reports that the resource already exists.

const (
	// IfExistsFail returns the conflict unchanged. It is the default and
	// preserves the historical behavior of every create command.
	IfExistsFail IfExistsMode = "fail"
	// IfExistsSkip treats the existing resource as success and leaves it
	// unchanged.
	IfExistsSkip IfExistsMode = "skip"
	// IfExistsUpdate routes the same inputs to the resource's update call.
	IfExistsUpdate IfExistsMode = "update"
)

type IncludedFieldFlags

type IncludedFieldFlags struct {
	// contains filtered or unexported fields
}

IncludedFieldFlags holds the sparse-field flags of the resources a command can include.

func BindIncludedFieldFlags

func BindIncludedFieldFlags(fs *flag.FlagSet, relationships map[string]string) *IncludedFieldFlags

BindIncludedFieldFlags binds one sparse-field flag per resource type. relationships maps each --include value to the resource type it returns.

func BindIncludedFieldFlagsExcept

func BindIncludedFieldFlagsExcept(fs *flag.FlagSet, relationships map[string]string, rejected map[string][]string) *IncludedFieldFlags

BindIncludedFieldFlagsExcept is BindIncludedFieldFlags without the fields[type] values, keyed by resource type, that Apple rejects on this command.

func (*IncludedFieldFlags) Resolve

func (f *IncludedFieldFlags) Resolve(command, next string, includes []string) (asc.IncludedFields, error)

Resolve validates the provided flags against --next and the resolved includes, and returns the requested fields per resource type.

func (*IncludedFieldFlags) ResolveWith

func (f *IncludedFieldFlags) ResolveWith(d *Deps, command, next string, includes []string) (asc.IncludedFields, error)

ResolveWith is Resolve with the "Error:" line written to d's stderr.

type JSONPayloadKind added in v1.260601.0

type JSONPayloadKind string

JSONPayloadKind describes the top-level JSON shape a raw payload command accepts.

const (
	JSONPayloadObject JSONPayloadKind = "object"
	JSONPayloadArray  JSONPayloadKind = "array"
	JSONPayloadAny    JSONPayloadKind = "any"
)

type JUnitReport

type JUnitReport struct {
	Tests     []JUnitTestCase // Test cases in this report
	Timestamp time.Time       // Report generation time
	Name      string          // Test suite name (default: "asc")
	// Duration optionally reports wall time for the whole suite. Leaf case
	// durations often exclude setup, teardown, and repeated or multi-destination
	// work, so their sum can understate the run. When Duration exceeds that sum
	// it is used for the suite time attribute; zero keeps the summed behavior.
	Duration time.Duration
}

JUnitReport represents a JUnit XML test report.

func ConsumeJUnitReport added in v1.260831.0

func ConsumeJUnitReport() *JUnitReport

ConsumeJUnitReport returns and clears the command-produced JUnit report.

func (*JUnitReport) Marshal

func (r *JUnitReport) Marshal() ([]byte, error)

Marshal marshals the JUnit report to XML. Note: xml.Encoder handles escaping automatically, so we don't pre-escape.

func (*JUnitReport) Write

func (r *JUnitReport) Write(path string) error

Write writes the JUnit report to the specified file path.

type JUnitTestCase

type JUnitTestCase struct {
	Name      string        // Test name (e.g., build-123)
	Classname string        // Test class/category (e.g., builds)
	Time      time.Duration // Test duration
	Skipped   bool          // Whether the test was skipped
	Failure   string        // Failure type (empty if passed)
	Message   string        // Failure message
	SystemOut string        // Standard output
	SystemErr string        // Standard error
}

JUnitTestCase represents a single test case in a JUnit report.

type LatestBuildSelectionOptions added in v1.260404.0

type LatestBuildSelectionOptions struct {
	AppID                 string
	Version               string
	Platform              string
	ProcessingStateValues []string
	ExcludeExpired        bool
	BuildAudienceType     asc.BuildAudienceType
}

LatestBuildSelectionOptions controls how latest/next build helpers select build records and in-flight uploads.

type ListCommandConfig

type ListCommandConfig struct {
	Name        string
	ShortUsage  string
	ShortHelp   string
	LongHelp    string
	ErrorPrefix string
	UsageFunc   func(*ffcli.Command) string
}

ListCommandConfig describes common help/output behavior for list-style CLI commands.

type LocalizationIncludeFlags

type LocalizationIncludeFlags struct {
	// contains filtered or unexported fields
}

LocalizationIncludeFlags holds the --include and --placements-limit flags of a localization read.

func BindLocalizationIncludeFlags

func BindLocalizationIncludeFlags(fs *flag.FlagSet, usage string, allowed []string) *LocalizationIncludeFlags

BindLocalizationIncludeFlags registers --include and --placements-limit.

func (*LocalizationIncludeFlags) Provided

func (f *LocalizationIncludeFlags) Provided() bool

Provided reports whether --include was set.

func (*LocalizationIncludeFlags) Resolve

func (f *LocalizationIncludeFlags) Resolve() ([]string, int, error)

Resolve validates the flags and returns the include list and placements limit.

func (*LocalizationIncludeFlags) ResolveWith

func (f *LocalizationIncludeFlags) ResolveWith(d *Deps) ([]string, int, error)

ResolveWith is Resolve with the "Error:" line written to d's stderr.

type MediaPollIntervalFlag

type MediaPollIntervalFlag struct {
	// contains filtered or unexported fields
}

MediaPollIntervalFlag is the --poll-interval flag shared by media uploads that wait for App Store Connect processing.

func BindMediaPollIntervalFlag

func BindMediaPollIntervalFlag(fs *flag.FlagSet) *MediaPollIntervalFlag

BindMediaPollIntervalFlag registers --poll-interval on fs.

func (*MediaPollIntervalFlag) Apply

Apply validates the flag and, when set, returns a context whose media processing waits poll at the requested fixed interval.

func (*MediaPollIntervalFlag) ApplyWith

func (f *MediaPollIntervalFlag) ApplyWith(ctx context.Context, d *Deps) (context.Context, error)

ApplyWith is Apply with the "Error:" line written to d's stderr.

type MetadataOutputFlags

type MetadataOutputFlags struct {
	OutputFormat *string
	Pretty       *bool
}

MetadataOutputFlags stores pointers to metadata output-related flag values.

func BindMetadataOutputFlags

func BindMetadataOutputFlags(fs *flag.FlagSet) MetadataOutputFlags

BindMetadataOutputFlags registers --output-format and --pretty flags on the provided flagset.

type MissingWebSessionError

type MissingWebSessionError struct {
	Message string
	Hint    string
}

MissingWebSessionError is the rendered form of ErrMissingWebSession. Hint carries the next step the root error renderer prints after the message.

func (*MissingWebSessionError) Error

func (e *MissingWebSessionError) Error() string

func (*MissingWebSessionError) Is

func (e *MissingWebSessionError) Is(target error) bool

Is lets errors.Is match ErrMissingWebSession through any wrapping.

func (*MissingWebSessionError) UsageErrorKind

func (e *MissingWebSessionError) UsageErrorKind() UsageErrorKind

UsageErrorKind classifies the failure as missing required input, as the usage errors it replaced were, so telemetry and command diagnostics keep their classification.

type MultiStringFlag added in v1.260404.0

type MultiStringFlag []string

MultiStringFlag collects repeatable string flag values while rejecting empty entries so callers can bind it directly with flag.FlagSet.Var.

func (*MultiStringFlag) Set added in v1.260404.0

func (m *MultiStringFlag) Set(value string) error

func (*MultiStringFlag) String added in v1.260404.0

func (m *MultiStringFlag) String() string

type NextBuildNumberOptions added in v1.260404.0

type NextBuildNumberOptions struct {
	LatestBuildSelectionOptions LatestBuildSelectionOptions
	InitialBuildNumber          int
}

NextBuildNumberOptions configures next build number calculation.

type OnceCSVValue added in v1.260819.0

type OnceCSVValue struct {
	// contains filtered or unexported fields
}

OnceCSVValue is a flag.Value for comma-separated list flags that rejects repeated flag occurrences instead of silently keeping only the last value.

func BindOnceCSVFlag added in v1.260819.0

func BindOnceCSVFlag(fs *flag.FlagSet, name, usage string) *OnceCSVValue

BindOnceCSVFlag registers a comma-separated list flag that errors when the flag is passed more than once.

func (*OnceCSVValue) Provided added in v1.260904.0

func (v *OnceCSVValue) Provided() bool

Provided reports whether the flag was set at least once, including values recovered after a space-separated boolean flag.

func (*OnceCSVValue) Set added in v1.260819.0

func (v *OnceCSVValue) Set(raw string) error

func (*OnceCSVValue) String added in v1.260819.0

func (v *OnceCSVValue) String() string

type OptionalBool

type OptionalBool struct {
	// contains filtered or unexported fields
}

OptionalBool tracks whether a boolean flag was explicitly set.

func (*OptionalBool) EnableBoolFlag

func (b *OptionalBool) EnableBoolFlag()

EnableBoolFlag allows bare --flag syntax for this OptionalBool instance.

func (*OptionalBool) IsBoolFlag

func (b *OptionalBool) IsBoolFlag() bool

IsBoolFlag tells the standard flag parser whether bare --flag is allowed.

func (OptionalBool) IsSet

func (b OptionalBool) IsSet() bool

func (*OptionalBool) Set

func (b *OptionalBool) Set(value string) error

func (*OptionalBool) String

func (b *OptionalBool) String() string

func (OptionalBool) Value

func (b OptionalBool) Value() bool

type OutputFileExistsError

type OutputFileExistsError struct {
	// contains filtered or unexported fields
}

OutputFileExistsError reports that a command refused to replace an existing output file. Choosing another path or removing the file is the fix, so it is a validation outcome rather than an asc defect.

func (*OutputFileExistsError) Diagnostic

func (e *OutputFileExistsError) Diagnostic() Diagnostic

func (*OutputFileExistsError) Error

func (e *OutputFileExistsError) Error() string

func (*OutputFileExistsError) Unwrap

func (e *OutputFileExistsError) Unwrap() error

func (*OutputFileExistsError) ValidationFailure

func (e *OutputFileExistsError) ValidationFailure() bool

type OutputFlags

type OutputFlags struct {
	Output *string
	Pretty *bool
}

OutputFlags stores pointers to output-related flag values.

func BindOutputFlagsWith

func BindOutputFlagsWith(fs *flag.FlagSet, flagName, defaultValue, usage string) OutputFlags

BindOutputFlagsWith registers a custom output-format flag and --pretty.

func BindOutputFlagsWithAllowed

func BindOutputFlagsWithAllowed(fs *flag.FlagSet, flagName, defaultValue, usage string, allowed ...string) OutputFlags

BindOutputFlagsWithAllowed registers a custom output-format flag and --pretty with an explicit allowed format set.

type PKCS12Encoding

type PKCS12Encoding string

PKCS12Encoding selects the algorithms used to protect a written .p12 identity.

const (
	PKCS12EncodingModern PKCS12Encoding = "modern"
	PKCS12EncodingLegacy PKCS12Encoding = "legacy"
)

func ParsePKCS12Encoding

func ParsePKCS12Encoding(value string) (PKCS12Encoding, error)

ParsePKCS12Encoding validates a --p12-encoding value.

type PPPScheduleSnapshot

type PPPScheduleSnapshot struct {
	BaseTerritory string
	Prices        []ResolvedPriceRow
}

PPPScheduleSnapshot retains the actual schedule base and complete forward prices.

type PaginatedListCommandConfig

type PaginatedListCommandConfig struct {
	// FlagSetName names the flag set, which parse errors show. It defaults
	// to Name.
	FlagSetName string
	Name        string
	ShortUsage  string
	ShortHelp   string
	LongHelp    string

	ParentFlag  string
	ParentUsage string
	// ParentType is the API resource type named by the parent flag. When set,
	// the flag also accepts that resource's self-link.
	ParentType string
	// TopLevel lists a collection that has no parent: no parent flag is
	// registered, and FetchPage receives an empty parent ID.
	TopLevel bool
	// ResolveApp reads the parent flag through ResolveAppID, which falls back
	// to ASC_APP_ID and the config file; a missing app is reported as
	// "--<flag> is required (or set ASC_APP_ID)".
	ResolveApp bool
	// LookupParent turns the parent ID into the ID FetchPage receives. It
	// runs after validation, once the client exists, and its error is
	// returned unwrapped. With --next it is skipped and FetchPage receives an
	// empty parent ID.
	LookupParent func(context.Context, *asc.Client, string) (string, error)
	// RequiredDiagnostic reports a missing parent flag with the
	// required-input diagnostic instead of a plain usage error.
	RequiredDiagnostic bool

	LimitMax int
	// PaginateIgnoresLimit makes --paginate request LimitMax items per page
	// even when --limit is set.
	PaginateIgnoresLimit bool
	// NoSpinner makes --paginate fetch without the stderr spinner. The first
	// page's error is then wrapped with FetchErrorPrefix, later pages' errors
	// with ErrorPrefix.
	NoSpinner bool

	// NextConflicts names flags that cannot be combined with --next.
	NextConflicts []string
	// Flags registers command-specific flags and returns their validation,
	// which runs after the --limit, --next and parent checks. The returned
	// function may be nil.
	Flags func(*flag.FlagSet) func() error

	// ErrorPrefix wraps the client error and the error of a --paginate
	// request after its first page. It defaults to the command path in
	// ShortUsage without "asc ".
	ErrorPrefix string
	// FetchErrorPrefix wraps the error of a single-page request. It defaults
	// to ErrorPrefix followed by ": failed to fetch".
	FetchErrorPrefix string

	// Deps supplies the client, streams and timeout.
	Deps *Deps

	ContextTimeout func(context.Context) (context.Context, context.CancelFunc)
	FetchPage      func(context.Context, *asc.Client, string, int, string) (asc.PaginatedResponse, error)
}

PaginatedListCommandConfig configures a standard list command with --limit/--next/--paginate and, unless TopLevel is set, a required parent resource ID.

type PlacementFilters

type PlacementFilters struct {
	// contains filtered or unexported fields
}

PlacementFilters holds the filter and sort flags of one placement list.

func BindPlacementFilters

func BindPlacementFilters(fs *flag.FlagSet, resource string) *PlacementFilters

BindPlacementFilters binds the filter and sort flags resource's placement list accepts.

func (*PlacementFilters) Apply

func (filters *PlacementFilters) Apply(query url.Values) error

Apply validates the provided flags and adds them to query. Omitted flags add nothing.

func (*PlacementFilters) Names

func (filters *PlacementFilters) Names() []string

Names returns the bound flag names for --next conflict checks.

type PriceFilter

type PriceFilter struct {
	Price    string
	MinPrice string
	MaxPrice string
}

PriceFilter holds parsed price filter criteria.

func (PriceFilter) HasFilter

func (pf PriceFilter) HasFilter() bool

HasFilter returns true if any price filter is set.

func (PriceFilter) MatchesPrice

func (pf PriceFilter) MatchesPrice(customerPrice string) bool

MatchesPrice returns true if the given customerPrice string passes the filter.

func (PriceFilter) Validate

func (pf PriceFilter) Validate() error

Validate checks that filter values are valid numbers and not contradictory.

type PriceLadderCandidate

type PriceLadderCandidate struct {
	PricePointID  string
	CustomerPrice string
}

type PriceLadderResolution

type PriceLadderResolution struct {
	PricePointID  string
	CustomerPrice string
	Price         *big.Rat
}

func ResolvePriceLadderPoint

func ResolvePriceLadderPoint(
	candidates []PriceLadderCandidate,
	desired *big.Rat,
	rounding PriceRounding,
) (PriceLadderResolution, error)

type PricePointEqualizationsCommandConfig added in v1.260407.0

type PricePointEqualizationsCommandConfig struct {
	FlagSetName string
	Name        string

	ShortUsage  string
	BaseExample string
	Subject     string

	ParentFlag  string
	ParentUsage string
	ParentType  string
	LimitMax    int

	ErrorPrefix string

	ContextTimeout func(context.Context) (context.Context, context.CancelFunc)
	// Deps supplies the client, streams and timeout.
	Deps *Deps
	// FetchPage receives the --include values for a first page and nil for a
	// links.next page, which already carries them. The client ignores the
	// sparse fields on a links.next page for the same reason.
	FetchPage func(context.Context, *asc.Client, string, int, string, []string, asc.IncludedFields) (asc.PaginatedResponse, error)
}

PricePointEqualizationsCommandConfig configures a standard equalizations list command for app, IAP, and subscription price points.

type PriceRounding

type PriceRounding string

PriceRounding selects how a calculated price resolves to an Apple price-point ladder.

const (
	PriceRoundingExact   PriceRounding = "exact"
	PriceRoundingNearest PriceRounding = "nearest"
	PriceRoundingUp      PriceRounding = "up"
	PriceRoundingDown    PriceRounding = "down"
)

type PriceSchedulePPPCommandConfig

type PriceSchedulePPPCommandConfig struct {
	FlagSetName  string
	ShortUsage   string
	ResourceNoun string
	Examples     string
	ErrorPrefix  string
	BindResource func(fs *flag.FlagSet) PriceSchedulePPPResource
	// Deps supplies the streams.
	Deps *Deps
}

PriceSchedulePPPCommandConfig configures pricing ppp and iap pricing ppp.

type PriceSchedulePPPResource

type PriceSchedulePPPResource struct {
	// Validate checks the resource flags before any request.
	Validate func() error
	// Resolve looks up the resource and returns its surface.
	Resolve func(ctx context.Context, client *asc.Client) (PriceSchedulePPPSurface, error)
}

PriceSchedulePPPResource binds a command's resource flags.

type PriceSchedulePPPSurface

type PriceSchedulePPPSurface struct {
	AppID string
	IAPID string
	// CurrentPrices returns each territory's effective price on the pricing
	// date containing at.
	CurrentPrices func(ctx context.Context, at time.Time) ([]ResolvedPriceRow, error)
	// ReadSchedule returns the complete forward schedule for scoped replacements.
	ReadSchedule func(ctx context.Context) (PPPScheduleSnapshot, error)
	// LadderBatch returns the price points of a batch of territories, keyed by
	// territory, reading every page.
	LadderBatch func(ctx context.Context, territories []string) (map[string][]PriceLadderCandidate, error)
	// LadderBatchSize is how many territories one LadderBatch call filters on.
	LadderBatchSize int
	// Equalizations returns Apple's equalized price points for the base price
	// point, keyed by territory.
	Equalizations func(ctx context.Context, pricePointID string) (map[string][]PriceLadderCandidate, error)
	// ReplaceSchedule creates a price schedule holding exactly prices.
	ReplaceSchedule func(ctx context.Context, baseTerritory string, prices []ScheduledPricePoint) error
	// PricePointKey maps a price point ID to a comparable key when current
	// prices name price points differently from the ladder; nil compares IDs.
	PricePointKey func(id string) string
}

PriceSchedulePPPSurface adapts an app or in-app purchase price schedule to the purchasing-power planner.

type PricingSetCommandConfig

type PricingSetCommandConfig struct {
	FlagSetName           string
	CommandName           string
	ShortUsage            string
	ShortHelp             string
	LongHelp              string
	ErrorPrefix           string
	StartDateHelp         string
	StartDateDefaultToday bool
	RequireBaseTerritory  bool
	ResolveBaseTerritory  bool
	// TemporaryPrice adds --end-date, --return-price-point, and --confirm.
	TemporaryPrice bool
	// Deps supplies the streams.
	Deps *Deps
}

PricingSetCommandConfig configures pricing set commands.

type ReconciledMutationStatus added in v1.260625.0

type ReconciledMutationStatus string

ReconciledMutationStatus describes whether a mutation response was observed directly or inferred from a matching readback after an ambiguous failure.

const (
	ReconciledMutationApplied   ReconciledMutationStatus = "applied"
	ReconciledMutationRecovered ReconciledMutationStatus = "reconciled"
)

func RunReconciledMutation added in v1.260625.0

func RunReconciledMutation[T any](
	ctx context.Context,
	mutate func(context.Context) (T, error),
	readback func(context.Context) (T, bool, error),
) (T, ReconciledMutationStatus, error)

RunReconciledMutation executes a mutation with a fresh request deadline. If the mutation fails ambiguously, it reads state immediately and once more after backoff before replaying the mutation. Readback callbacks may span pagination and are responsible for fresh per-request deadlines.

func RunReconciledMutationNoReplayWith

func RunReconciledMutationNoReplayWith[T any](
	ctx context.Context,
	d *Deps,
	mutate func(context.Context) (T, error),
	readback func(context.Context) (T, bool, error),
) (T, ReconciledMutationStatus, error)

RunReconciledMutationNoReplayWith executes an ambiguous mutation once and uses immediate and one delayed readback to determine whether that attempt applied. It never replays a mutation after a negative readback. Deterministic failures are returned directly so strict API errors keep their existing classification. The mutation's deadline comes from d.Timeout and the backoff runs on d.After.

func RunReconciledMutationWith

func RunReconciledMutationWith[T any](
	ctx context.Context,
	d *Deps,
	mutate func(context.Context) (T, error),
	readback func(context.Context) (T, bool, error),
) (T, ReconciledMutationStatus, error)

RunReconciledMutationWith is RunReconciledMutation with each mutation's deadline from d.Timeout and the backoff on d.After.

type RelationshipParent

type RelationshipParent struct {
	// ResourceType is Apple's resource type as it appears in a 404 detail,
	// such as "builds" or "betaGroups".
	ResourceType string
	// Label is the human-readable resource name used in the message, such as
	// "build" or "beta group".
	Label string
	// ID is the parent resource ID the request addressed. It is empty when a
	// next-page URL, not an ID flag, addressed the request.
	ID string
	// Hint is optional flag guidance appended to the unknown-parent message.
	Hint string
	// RelationshipResourceTypes are the JSON:API resource types that can back
	// the selected relationship. Set this when the relationship path and
	// resource type do not share the same name, such as icons and buildIcons.
	RelationshipResourceTypes []string
}

RelationshipParent identifies the resource whose relationship linkages a links command requested, so a 404 can name what App Store Connect could not find.

type ReportedError

type ReportedError interface {
	error
	Reported() bool
}

ReportedError marks an error whose result the command already reported, usually as structured output on stdout. The root still prints one stderr error line unless the error is also marked as printed to stderr.

type ReportedUsageError added in v1.260816.0

type ReportedUsageError interface {
	ReportedError
	UsageErrorKind() UsageErrorKind
}

ReportedUsageError marks an already-printed usage failure without wrapping flag.ErrHelp. This lets commands provide concise corrective guidance while preserving usage exit and telemetry semantics without triggering full help.

type ResolveBetaGroupsOptions

type ResolveBetaGroupsOptions struct {
	SkipInternal            bool
	IncludeSkipInternalHint bool
}

ResolveBetaGroupsOptions controls beta-group name resolution behavior.

type ResolvedAuthCredentials

type ResolvedAuthCredentials struct {
	KeyID    string
	IssuerID string
	KeyPath  string
	KeyPEM   string
	KeyType  string
	Profile  string
}

ResolvedAuthCredentials contains the concrete auth inputs selected for a command.

func ResolveAuthCredentials

func ResolveAuthCredentials(profile string) (ResolvedAuthCredentials, error)

ResolveAuthCredentials resolves the signing credentials for a command. A non-empty profile override takes precedence over root-level profile selection.

func ResolveAuthCredentialsMetadata added in v1.260328.0

func ResolveAuthCredentialsMetadata(profile string) (ResolvedAuthCredentials, error)

ResolveAuthCredentialsMetadata resolves the selected auth profile's key metadata without loading private key material from keychain or disk.

type ResolvedBetaGroup

type ResolvedBetaGroup struct {
	ID                   string
	Name                 string
	IsInternalGroup      bool
	HasAccessToAllBuilds bool
}

ResolvedBetaGroup captures the canonical ID and metadata for a beta group.

func ResolveBetaGroups

func ResolveBetaGroups(ctx context.Context, client betaGroupsClient, appID, rawGroups string, opts ResolveBetaGroupsOptions) ([]ResolvedBetaGroup, error)

ResolveBetaGroups lists an app's beta groups and resolves a raw --group value. A value that exactly matches one group ID or name is used as-is, even when it contains commas; otherwise the value is treated as a comma-separated list of group names or IDs.

func ResolveBetaGroupsFromList

func ResolveBetaGroupsFromList(inputGroups []string, groups *asc.BetaGroupsResponse, opts ResolveBetaGroupsOptions) ([]ResolvedBetaGroup, error)

ResolveBetaGroupsFromList resolves IDs or names against a provided beta-groups payload.

func (ResolvedBetaGroup) NameForDisplay

func (g ResolvedBetaGroup) NameForDisplay() string

type ResolvedPriceRow added in v1.260331.0

type ResolvedPriceRow struct {
	Territory     string `json:"territory"`
	PlanType      string `json:"planType,omitempty"`
	PriceID       string `json:"priceId"`
	PricePointID  string `json:"pricePointId"`
	CustomerPrice string `json:"customerPrice,omitempty"`
	Currency      string `json:"currency,omitempty"`
	Proceeds      string `json:"proceeds,omitempty"`
	ProceedsYear2 string `json:"proceedsYear2,omitempty"`
	StartDate     string `json:"startDate,omitempty"`
	EndDate       string `json:"endDate,omitempty"`
	Manual        *bool  `json:"manual,omitempty"`
	Preserved     *bool  `json:"preserved,omitempty"`
}

ResolvedPriceRow represents the currently effective price for a territory.

func SelectPPPCurrentPrices

func SelectPPPCurrentPrices(prices []ResolvedPriceRow, territories []string, at time.Time) ([]ResolvedPriceRow, error)

SelectPPPCurrentPrices requires every requested territory to be currently priced.

type ResolvedPricesResult added in v1.260331.0

type ResolvedPricesResult struct {
	Prices []ResolvedPriceRow `json:"prices"`
}

ResolvedPricesResult is the command-local response envelope for --resolved pricing.

type ReviewSubmissionNotCancellableError

type ReviewSubmissionNotCancellableError struct {
	SubmissionID string
	State        asc.ReviewSubmissionState
	Err          error
}

ReviewSubmissionNotCancellableError explains why App Store Connect refused to cancel a review submission, using the state read after the refusal. It wraps the original API error so exit codes and error matching are unchanged.

func (*ReviewSubmissionNotCancellableError) Error

func (*ReviewSubmissionNotCancellableError) Unwrap

type ScheduledPricePoint

type ScheduledPricePoint struct {
	PricePointID string
	StartDate    string
	EndDate      string
}

ScheduledPricePoint is one manual price in a replacement price schedule.

type SubmitReadinessCreateWarning added in v1.260407.0

type SubmitReadinessCreateWarning struct {
	Locale        string
	Mode          string
	MissingFields []string
}

SubmitReadinessCreateWarning describes create-scope submission risk for one locale.

func NormalizeSubmitReadinessCreateWarnings added in v1.260407.0

func NormalizeSubmitReadinessCreateWarnings(warnings []SubmitReadinessCreateWarning) []SubmitReadinessCreateWarning

NormalizeSubmitReadinessCreateWarnings sorts and dedupes warnings so callers can emit them deterministically after their main output succeeds.

func SubmitReadinessCreateWarningForLocaleWithOptions added in v1.260407.0

func SubmitReadinessCreateWarningForLocaleWithOptions(locale string, attrs asc.AppStoreVersionLocalizationAttributes, mode string, opts SubmitReadinessOptions) (SubmitReadinessCreateWarning, bool)

SubmitReadinessCreateWarningForLocaleWithOptions returns a create warning when the provided attributes would leave the locale incomplete for submission.

type SubmitReadinessIssue

type SubmitReadinessIssue struct {
	Locale        string
	MissingFields []string
}

SubmitReadinessIssue describes submission-blocking missing fields for a locale.

func SubmitReadinessIssuesByLocaleWithOptions

func SubmitReadinessIssuesByLocaleWithOptions(localizations []asc.Resource[asc.AppStoreVersionLocalizationAttributes], opts SubmitReadinessOptions) []SubmitReadinessIssue

SubmitReadinessIssuesByLocaleWithOptions evaluates all localizations with configurable checks and returns per-locale missing submit-required fields.

type SubmitReadinessOptions

type SubmitReadinessOptions struct {
	// RequireWhatsNew enables whatsNew validation. This should be set for
	// app updates (when a released version already exists) because
	// App Store Connect requires whatsNew for every locale on updates.
	RequireWhatsNew bool
}

SubmitReadinessOptions controls optional submit-readiness checks.

func ResolveSubmitReadinessOptionsForVersion added in v1.260407.0

func ResolveSubmitReadinessOptionsForVersion(ctx context.Context, client *asc.Client, versionID, appID, platform string) (SubmitReadinessOptions, error)

ResolveSubmitReadinessOptionsForVersion resolves create-warning options for a version-localization workflow. Callers that only need advisory warnings should prefer the best-effort wrapper so auxiliary fetch failures do not block the primary mutation.

func ResolveSubmitReadinessOptionsForVersionBestEffort added in v1.260407.0

func ResolveSubmitReadinessOptionsForVersionBestEffort(ctx context.Context, client *asc.Client, versionID, appID, platform string) SubmitReadinessOptions

ResolveSubmitReadinessOptionsForVersionBestEffort resolves create-warning options without failing the caller when advisory context fetches fail.

type TerritoryAvailabilityUpdateRequest

type TerritoryAvailabilityUpdateRequest struct {
	// AppID is the App Store Connect app whose availability is updated.
	AppID string
	// Territories lists the territories to change. Ignored when AllTerritories
	// is set.
	Territories []string
	// AllTerritories applies the change to every territory in the record.
	AllTerritories bool
	// Available is the availability value applied to the selected territories.
	Available bool
	// ExpectedAvailableInNewTerritories, when set, verifies the record's
	// existing new-territory policy. Apple exposes no update operation for it.
	ExpectedAvailableInNewTerritories *bool
	// ErrorPrefix prefixes returned errors, for example "pricing availability create".
	ErrorPrefix string
}

TerritoryAvailabilityUpdateRequest describes a territory availability change applied to an app's existing availability record.

type TestNotesNormalization

type TestNotesNormalization struct {
	Notes                 string
	Changed               bool
	RemovedAngleBrackets  bool
	RemovedCombiningMarks bool
}

TestNotesNormalization reports the What to Test text that will be stored and which characters App Store Connect rejects were dropped to reach it.

func NormalizeTestNotes

func NormalizeTestNotes(notes string) (TestNotesNormalization, error)

NormalizeTestNotes rewrites What to Test notes into the form App Store Connect accepts: NFC-composed text without "<" characters or leftover generic combining diacritics (see isRejectedTestNotesMark). Script-specific marks such as Devanagari, Thai, Hebrew, and Arabic vowel signs are kept. Characters App Store Connect refuses in whatsNew, such as emoji, pictographic symbols, and variation selectors (see rejectedTestNotesRunes), are a usage failure that names them instead of silently changing the operator's text. Notes that keep no usable character are also a usage failure, so the caller never sends a request Apple is certain to reject.

func (TestNotesNormalization) Notice

func (n TestNotesNormalization) Notice() string

Notice returns a single-line operator notice for a normalization that changed the stored text, or an empty string when the text was kept as submitted. It never includes the notes themselves.

type TestNotesRecoveryError added in v1.260825.0

type TestNotesRecoveryError struct {
	// contains filtered or unexported fields
}

TestNotesRecoveryError preserves a discovered build and the exact retry arguments while keeping its human-facing diagnostic terminal-safe.

func NewTestNotesRecoveryError added in v1.260825.0

func NewTestNotesRecoveryError(buildID, locale, notes string, cause error) *TestNotesRecoveryError

NewTestNotesRecoveryError returns recovery context for a failed post-upload What to Test request.

func (*TestNotesRecoveryError) Error added in v1.260825.0

func (e *TestNotesRecoveryError) Error() string

func (*TestNotesRecoveryError) Recovery added in v1.260825.0

Recovery returns exact, shell-neutral retry data for structured output.

func (*TestNotesRecoveryError) Unwrap added in v1.260825.0

func (e *TestNotesRecoveryError) Unwrap() error

Unwrap preserves API error status and exit classification.

type TierEntry

type TierEntry struct {
	Tier          int    `json:"tier"`
	PricePointID  string `json:"pricePointId"`
	CustomerPrice string `json:"customerPrice"`
	Proceeds      string `json:"proceeds"`
}

TierEntry represents a single tier in a territory's price point list.

func LoadTierCache

func LoadTierCache(appID, territory string) ([]TierEntry, error)

LoadTierCache loads cached tier data. Returns an error if the cache is missing or expired.

type TimeoutSetting

type TimeoutSetting int

TimeoutSetting names a timeout a user sets in the environment or the config file.

const (
	// RequestTimeoutSetting is ASC_TIMEOUT or ASC_TIMEOUT_SECONDS, or timeout
	// or timeout_seconds in the config file.
	RequestTimeoutSetting TimeoutSetting = iota
	// UploadTimeoutSetting is ASC_UPLOAD_TIMEOUT or ASC_UPLOAD_TIMEOUT_SECONDS,
	// or upload_timeout or upload_timeout_seconds in the config file.
	UploadTimeoutSetting
)

type UpsertBetaBuildLocalizationOptions

type UpsertBetaBuildLocalizationOptions struct {
	// AppID identifies the build's app. When empty, the app is resolved from
	// the build so the locale's TestFlight app localization can be ensured.
	AppID string
	// Diagnostics receives a one-line notice when a missing TestFlight app
	// localization is created as a side effect. Nil discards the notice.
	Diagnostics io.Writer
}

UpsertBetaBuildLocalizationOptions carries caller context for a What to Test write.

type UsageErrorKind added in v1.260628.0

type UsageErrorKind string
const (
	UsageErrorMissingRequired UsageErrorKind = "missing_required"
	UsageErrorInvalidValue    UsageErrorKind = "invalid_value"
	UsageErrorOther           UsageErrorKind = "other"
)

func ClassifyUsageError added in v1.260628.0

func ClassifyUsageError(err error) UsageErrorKind

type UsageMessageRewrite added in v1.260904.0

type UsageMessageRewrite struct {
	// Old is the text to replace. A rewrite with an empty Old or New, or with
	// Old equal to New, is ignored.
	Old string
	// New is the replacement text.
	New string
	// AnchoredPrefix replaces only a single leading occurrence of Old, matching
	// rewriteCommandErrorPrefix. Without it every occurrence is replaced,
	// matching the TestFlight wrappers' text replacements.
	AnchoredPrefix bool
}

UsageMessageRewrite renames a command path inside a usage diagnostic.

Several command trees are re-parented after construction, by RewriteCommandTreePath here and by the TestFlight command wrappers. Both rewrite help text and, for a command that returns an ordinary error, the message that error renders, so an operator sees the command path they typed rather than the one the command was originally written under.

A usage error cannot travel that path. UsageError writes "Error: <message>" to stderr while the command is still running and returns an error wrapping flag.ErrHelp, which both rewriters skip and neither can un-print. A command under a re-parented tree therefore installs its rewrites on the context, and UsageErrorCtx applies them before the diagnostic reaches stderr. Call sites keep the literal command path they were written with, which the raw per-command tests assert directly.

type ValidationFailure added in v1.260701.0

type ValidationFailure interface {
	error
	ValidationFailure() bool
}

ValidationFailure marks an error as a command/domain validation result rather than a generic runtime failure. It intentionally carries no command-specific value so telemetry can classify the stage without increasing cardinality.

type VersionLocalization

type VersionLocalization struct {
	ID     string
	Locale string
	Values map[string]string
}

VersionLocalization holds a localization's values keyed by import field name.

type VersionLocalizationImportConfig

type VersionLocalizationImportConfig struct {
	// CommandPath is the command path after "asc", such as
	// "iap versions localizations import".
	CommandPath         string
	VersionResourceType string
	VersionFlagUsage    string
	ResourceType        string
	// OptionalField is the import field besides "name", such as "description".
	OptionalField string
	ExampleValues string
	NewClient     func() (*asc.Client, error)
	Ops           func(*asc.Client) VersionLocalizationImportOps
	// Deps supplies the streams, the request timeout and the output. The
	// client comes from NewClient.
	Deps *Deps
}

VersionLocalizationImportConfig configures a version-scoped localizations import command.

type VersionLocalizationImportOps

type VersionLocalizationImportOps struct {
	List   func(ctx context.Context, versionID string) ([]VersionLocalization, error)
	Create func(ctx context.Context, versionID, locale string, values map[string]string) (string, error)
	Update func(ctx context.Context, localizationID string, values map[string]string) error
}

VersionLocalizationImportOps performs the API calls for one localization resource. Create receives every value from the file; Update receives only the values that differ from App Store Connect.

type VersionMetadataCopyOptions

type VersionMetadataCopyOptions struct {
	AppID                string
	Platform             string
	SourceVersion        string
	DestinationVersionID string
	SelectedFields       []string
	DryRun               bool
}

VersionMetadataCopyOptions defines a metadata carry-forward operation between App Store versions.

type WriteCommandConfig

type WriteCommandConfig struct {
	// FlagSetName names the flag set, which parse errors show. It defaults
	// to Name.
	FlagSetName string
	Name        string
	ShortUsage  string
	ShortHelp   string
	LongHelp    string

	// ErrorPrefix wraps the client error and the request error. It defaults
	// to the command path in ShortUsage without "asc ".
	ErrorPrefix string

	// IDFlag names the required ID flag: the parent resource of a create,
	// the resource itself of an update. It defaults to "id".
	IDFlag  string
	IDUsage string
	// IDType is the API resource type named by the ID flag; see
	// IDGetCommandConfig.IDType.
	IDType string
	// TopLevel creates a resource that has no parent: no ID flag is
	// registered, and Send receives an empty ID.
	TopLevel bool

	// Fields are the request's flags, checked in this order after the ID.
	Fields []AttributeFlag

	// Deps supplies the client, streams and timeout.
	Deps *Deps

	// Send makes the request for the ID flag's value once every field has
	// been written to its target.
	Send func(context.Context, *asc.Client, string) (any, error)
}

WriteCommandConfig configures a create or update command that sends one request built from string flags.

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL