Skip to content

discovery

napt.discovery

Discovery package: strategies, registry, and orchestration.

Two flows feed into discover_recipe:

  • Version-first strategies (api_github, api_json, web_scrape) implement DiscoveryStrategy: they discover a version and its download URL without touching the file. The orchestrator looks them up in the explicit table in napt.discovery.registry.
  • url_download is a separate flow at run_url_download. It is not in the registry because it cannot determine the version without the file.

Both end in resolve_installer, which reuses the previous download when nothing changed, and otherwise downloads the file, reads the version from an MSI or MSIX installer, and files it under that version.

The discovery orchestrator dispatches to one of the two flows based on the recipe's discovery.strategy value.

Built-in strategies
  • api_github: queries the GitHub releases API for the latest tag.
  • api_json: extracts version and download URL from a JSON endpoint.
  • web_scrape: parses a vendor download page for both fields.

napt.discovery.base

Discovery strategy protocol and shared helpers.

A discovery strategy answers a single question: "what is the latest version of this app, and where can it be downloaded from?" Strategies return that answer as a RemoteVersion dataclass. They do not download files themselves; the orchestrator does.

Built-in strategies
  • api_github: queries the GitHub releases API for the latest tag.
  • api_json: extracts version and download URL from a JSON endpoint.
  • web_scrape: parses a vendor download page for both fields.

The fourth flow (url_download) is not a registered strategy. It downloads a fixed URL and extracts the version from the file itself, which is a different shape than the strategies in this module. The discovery orchestrator dispatches to that flow directly when a recipe uses strategy: url_download.

Design Philosophy
  • Strategies are typing.Protocol types. Implementations are matched structurally; no inheritance is required.
  • Strategies are pure functions of configuration. They have no state and no I/O of files.
  • Dispatch is an explicit name-to-class table in napt.discovery.registry.
  • resolve_installer turns a RemoteVersion into a StrategyResult by reusing the previous download or fetching a new one. Strategies don't call it themselves; the orchestrator does.

RemoteVersion dataclass

Version and download URL discovered from a remote source.

Returned by every DiscoveryStrategy implementation. The orchestrator passes this to resolve_installer to decide whether the file needs to be downloaded.

Attributes:

Name Type Description
version str

Raw version string extracted from the remote source (for example, "140.0.7339.128"). The trigger for a download; an MSI or MSIX installer's own version is what gets recorded.

download_url str

URL the installer can be fetched from.

source str

Name of the strategy that produced this result, used for logging and result reporting (for example, "api_github").

Source code in napt/discovery/base.py
@dataclass(frozen=True)
class RemoteVersion:
    """Version and download URL discovered from a remote source.

    Returned by every [DiscoveryStrategy][napt.discovery.base.DiscoveryStrategy]
    implementation. The orchestrator passes this to
    [resolve_installer][napt.discovery.resolve.resolve_installer] to decide
    whether the file needs to be downloaded.

    Attributes:
        version: Raw version string extracted from the remote source
            (for example, ``"140.0.7339.128"``). The trigger for a
            download; an MSI or MSIX installer's own version is what gets
            recorded.
        download_url: URL the installer can be fetched from.
        source: Name of the strategy that produced this result, used
            for logging and result reporting (for example, ``"api_github"``).
    """

    version: str
    download_url: str
    source: str

StrategyResult dataclass

Resolved discovery result, ready to be recorded in deployment state.

Returned by resolve_installer for every flow. Captures everything the orchestrator needs to record the pending release and build a public DiscoverResult.

Attributes:

Name Type Description
version str

Version string for the resolved file.

version_source str

Where the version came from: "msi" or "msix" when read from the installer, otherwise the name of the strategy that reported it (for example, "api_github").

file_path Path

Path to the resolved installer on disk. This is either a freshly downloaded file or one an earlier run downloaded.

sha256 str

SHA-256 hex digest of the resolved file.

download_url str

URL the file came from, recorded with the pending release.

Source code in napt/discovery/base.py
@dataclass(frozen=True)
class StrategyResult:
    """Resolved discovery result, ready to be recorded in deployment state.

    Returned by [resolve_installer][napt.discovery.resolve.resolve_installer]
    for every flow. Captures everything the orchestrator needs to record
    the pending release and build a public
    [DiscoverResult][napt.discovery.manager.DiscoverResult].

    Attributes:
        version: Version string for the resolved file.
        version_source: Where the version came from: ``"msi"`` or
            ``"msix"`` when read from the installer, otherwise the name of
            the strategy that reported it (for example, ``"api_github"``).
        file_path: Path to the resolved installer on disk. This is either
            a freshly downloaded file or one an earlier run downloaded.
        sha256: SHA-256 hex digest of the resolved file.
        download_url: URL the file came from, recorded with the pending
            release.
    """

    version: str
    version_source: str
    file_path: Path
    sha256: str
    download_url: str

DiscoveryStrategy

Bases: Protocol

Protocol for version discovery strategies.

A strategy queries a remote source (API, web page, etc.) and returns the latest version plus its download URL. Strategies do not download files or write to disk. Those concerns belong to the orchestrator.

Implementations need FIELDS, a discover and a validate_config method with the signatures below. The config loader runs validate_config on the merged configuration and stops on any error before discover is called, so discover reads its fields directly.

Attributes:

Name Type Description
FIELDS frozenset[str]

Every discovery field the strategy reads, besides strategy. Validation warns on any other key.

Source code in napt/discovery/base.py
class DiscoveryStrategy(Protocol):
    """Protocol for version discovery strategies.

    A strategy queries a remote source (API, web page, etc.) and returns
    the latest version plus its download URL. Strategies do not download
    files or write to disk. Those concerns belong to the orchestrator.

    Implementations need ``FIELDS``, a ``discover`` and a
    ``validate_config`` method with the signatures below. The config
    loader runs ``validate_config`` on the merged configuration and stops
    on any error before ``discover`` is called, so ``discover`` reads its
    fields directly.

    Attributes:
        FIELDS: Every ``discovery`` field the strategy reads, besides
            ``strategy``. Validation warns on any other key.
    """

    FIELDS: ClassVar[frozenset[str]]

    def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
        """Discovers the latest version and its download URL.

        Args:
            app_config: Merged and validated recipe configuration dict.

        Returns:
            Latest version, the URL it can be downloaded from, and the
            strategy's own name as the source identifier.

        Raises:
            ConfigError: When the remote data does not match the recipe's
                patterns or paths.
            NetworkError: On request failures, or remote values too long to
                match a pattern on.

        """
        ...

    def validate_config(self, app_config: dict[str, Any]) -> list[str]:
        """Validates strategy-specific configuration fields without network calls.

        Implementations should check field presence, types, and format only.

        Args:
            app_config: Merged recipe configuration dict.

        Returns:
            Human-readable error messages. Empty when configuration is valid.

        """
        ...

discover

discover(app_config: dict[str, Any]) -> RemoteVersion

Discovers the latest version and its download URL.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged and validated recipe configuration dict.

required

Returns:

Type Description
RemoteVersion

Latest version, the URL it can be downloaded from, and the

RemoteVersion

strategy's own name as the source identifier.

Raises:

Type Description
ConfigError

When the remote data does not match the recipe's patterns or paths.

NetworkError

On request failures, or remote values too long to match a pattern on.

Source code in napt/discovery/base.py
def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
    """Discovers the latest version and its download URL.

    Args:
        app_config: Merged and validated recipe configuration dict.

    Returns:
        Latest version, the URL it can be downloaded from, and the
        strategy's own name as the source identifier.

    Raises:
        ConfigError: When the remote data does not match the recipe's
            patterns or paths.
        NetworkError: On request failures, or remote values too long to
            match a pattern on.

    """
    ...

validate_config

validate_config(app_config: dict[str, Any]) -> list[str]

Validates strategy-specific configuration fields without network calls.

Implementations should check field presence, types, and format only.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged recipe configuration dict.

required

Returns:

Type Description
list[str]

Human-readable error messages. Empty when configuration is valid.

Source code in napt/discovery/base.py
def validate_config(self, app_config: dict[str, Any]) -> list[str]:
    """Validates strategy-specific configuration fields without network calls.

    Implementations should check field presence, types, and format only.

    Args:
        app_config: Merged recipe configuration dict.

    Returns:
        Human-readable error messages. Empty when configuration is valid.

    """
    ...

first_capture

first_capture(pattern: Pattern[str], text: str) -> str | None

Returns what a recipe pattern captures from a remote string.

A pattern with capture groups yields group 1, otherwise the whole match. A group that took no part in the match (an optional group whose text was absent) counts as no match: it would otherwise turn into the text None or a missing link.

Parameters:

Name Type Description Default
pattern Pattern[str]

The compiled recipe pattern.

required
text str

The string to search.

required

Returns:

Type Description
str | None

The captured text, or None when the pattern did not match.

Source code in napt/discovery/base.py
def first_capture(pattern: re.Pattern[str], text: str) -> str | None:
    """Returns what a recipe pattern captures from a remote string.

    A pattern with capture groups yields group 1, otherwise the whole
    match. A group that took no part in the match (an optional group whose
    text was absent) counts as no match: it would otherwise turn into the
    text ``None`` or a missing link.

    Args:
        pattern: The compiled recipe pattern.
        text: The string to search.

    Returns:
        The captured text, or None when the pattern did not match.
    """
    match = pattern.search(text)
    if match is None:
        return None
    return match.group(1) if pattern.groups else match.group(0)

bounded

bounded(value: str, what: str) -> str

Returns a remote string once it is short enough to match a pattern on.

Parameters:

Name Type Description Default
value str

The string a recipe pattern will run over.

required
what str

What the string is, for the error message.

required

Returns:

Type Description
str

The value unchanged.

Raises:

Type Description
NetworkError

If the value is longer than MAX_PATTERN_INPUT.

Source code in napt/discovery/base.py
def bounded(value: str, what: str) -> str:
    """Returns a remote string once it is short enough to match a pattern on.

    Args:
        value: The string a recipe pattern will run over.
        what: What the string is, for the error message.

    Returns:
        The value unchanged.

    Raises:
        NetworkError: If the value is longer than ``MAX_PATTERN_INPUT``.
    """
    if len(value) > MAX_PATTERN_INPUT:
        raise NetworkError(
            f"{what} is {len(value)} characters long; NAPT matches recipe "
            f"patterns against at most {MAX_PATTERN_INPUT}"
        )
    return value

require_usable_version

require_usable_version(version: str) -> None

Rejects a version that cannot name a folder or that a device would misread.

The version names the download folder (downloads/<id>/<version>) and later the build folder, so a value with a path separator or .. is refused before any folder is created from it.

It is also what the detection and requirements scripts compare on a device, and they take each part's leading digits with a part that has none counting as 0. A version whose first part has no digits (v2.0, latest) therefore reads as version 0 there: every device would report it installed and no device would ever upgrade to it. Such a version is refused so the recipe gets fixed instead. The scripts cast each part to a 64-bit integer, so a part of more than 18 digits, which may not fit, is refused as well.

Parameters:

Name Type Description Default
version str

Version read from the installer, or reported by a strategy for an installer that carries no version of its own.

required

Raises:

Type Description
ConfigError

If the version is not a plain folder name, does not start with a digit, or has a part of more than 18 digits.

Source code in napt/discovery/base.py
def require_usable_version(version: str) -> None:
    """Rejects a version that cannot name a folder or that a device would misread.

    The version names the download folder (``downloads/<id>/<version>``)
    and later the build folder, so a value with a path separator or ``..``
    is refused before any folder is created from it.

    It is also what the detection and requirements scripts compare on a
    device, and they take each part's leading digits with a part that has
    none counting as 0. A version whose first part has no digits (``v2.0``,
    ``latest``) therefore reads as version 0 there: every device would
    report it installed and no device would ever upgrade to it. Such a
    version is refused so the recipe gets fixed instead. The scripts cast
    each part to a 64-bit integer, so a part of more than 18 digits, which
    may not fit, is refused as well.

    Args:
        version: Version read from the installer, or reported by a
            strategy for an installer that carries no version of its own.

    Raises:
        ConfigError: If the version is not a plain folder name, does not
            start with a digit, or has a part of more than 18 digits.
    """
    if not is_safe_path_component(version):
        raise ConfigError(
            f"Discovered version {version!a} cannot be used as a folder name. "
            "Versions may contain only letters, digits, '.', '-', '_', and '+'. "
            "Check the recipe's version pattern, or the installer's metadata."
        )
    if not version[0].isdigit():
        # The part from the first digit onward is what a pattern should keep.
        digits = re.search(r"\d.*", version)
        hint = (
            f"Tighten the recipe's version_pattern so it captures only "
            f"{digits.group()!a}."
            if digits
            else "Check the recipe's version_path or version_pattern."
        )
        raise ConfigError(
            f"Version {version!a} does not start with a number. Devices compare "
            "versions numerically and would read it as 0, which blocks "
            f"upgrades. {hint}"
        )
    for segment in re.split(r"[.\-]", version):
        digits = re.match(r"\d+", segment)
        if digits and len(digits.group()) > 18:
            raise ConfigError(
                f"Version {version!a} has a part with more than 18 digits "
                f"({digits.group()!a}). Devices compare version parts as 64-bit "
                "integers, and their detection script would fail on it. Check "
                "the recipe's version pattern, or the installer's metadata."
            )

napt.discovery.fields

Field checks and the request helper the discovery strategies share.

Every strategy's validate_config reports the same three things about a field (missing, wrong type, empty) and compiles the same kinds of pattern, and every version-first strategy fetches one URL the same way. Those live here so each strategy holds only its own rules, and so a message about discovery.repo reads like the messages napt.validation produces for every other section.

Validation runs before any discover method is called: the config loader validates the merged configuration and refuses to continue on any error. A discover method therefore reads its fields directly and checks only what the remote data turns out to be.

require_str

require_str(source: dict[str, Any], key: str, errors: list[str]) -> str | None

Checks that a required field is present and a non-empty string.

Parameters:

Name Type Description Default
source dict[str, Any]

The discovery section.

required
key str

The field name.

required
errors list[str]

List to append errors to.

required

Returns:

Type Description
str | None

The value when it passes, otherwise None.

Source code in napt/discovery/fields.py
def require_str(source: dict[str, Any], key: str, errors: list[str]) -> str | None:
    """Checks that a required field is present and a non-empty string.

    Args:
        source: The ``discovery`` section.
        key: The field name.
        errors: List to append errors to.

    Returns:
        The value when it passes, otherwise None.
    """
    if key not in source:
        errors.append(f"discovery: Missing required field: {key}")
        return None
    return optional_str(source, key, errors)

optional_str

optional_str(source: dict[str, Any], key: str, errors: list[str]) -> str | None

Checks that a field, when present, is a non-empty string.

Parameters:

Name Type Description Default
source dict[str, Any]

The discovery section.

required
key str

The field name.

required
errors list[str]

List to append errors to.

required

Returns:

Type Description
str | None

The value when present and valid, otherwise None.

Source code in napt/discovery/fields.py
def optional_str(source: dict[str, Any], key: str, errors: list[str]) -> str | None:
    """Checks that a field, when present, is a non-empty string.

    Args:
        source: The ``discovery`` section.
        key: The field name.
        errors: List to append errors to.

    Returns:
        The value when present and valid, otherwise None.
    """
    if key not in source:
        return None
    value = source[key]
    if not isinstance(value, str):
        errors.append(f"discovery.{key}: Must be a string")
        return None
    if not value.strip():
        errors.append(f"discovery.{key}: Must be a non-empty string")
        return None
    return value

check_regex

check_regex(value: str, key: str, errors: list[str]) -> None

Checks that a field's value compiles as a regular expression.

Parameters:

Name Type Description Default
value str

The pattern text.

required
key str

The field name, for the message.

required
errors list[str]

List to append errors to.

required
Source code in napt/discovery/fields.py
def check_regex(value: str, key: str, errors: list[str]) -> None:
    """Checks that a field's value compiles as a regular expression.

    Args:
        value: The pattern text.
        key: The field name, for the message.
        errors: List to append errors to.
    """
    try:
        re.compile(value)
    except re.error as err:
        errors.append(f"discovery.{key}: Invalid regex: {err}")

check_format

check_format(value: str, key: str, errors: list[str]) -> None

Checks that a field's value is a format string over capture groups.

The groups are passed by position, so every replacement field must be a number ({0}, {1}) or empty ({}); a named field would fail at discovery time.

Parameters:

Name Type Description Default
value str

The format string.

required
key str

The field name, for the message.

required
errors list[str]

List to append errors to.

required
Source code in napt/discovery/fields.py
def check_format(value: str, key: str, errors: list[str]) -> None:
    """Checks that a field's value is a format string over capture groups.

    The groups are passed by position, so every replacement field must be
    a number (``{0}``, ``{1}``) or empty (``{}``); a named field would
    fail at discovery time.

    Args:
        value: The format string.
        key: The field name, for the message.
        errors: List to append errors to.
    """
    try:
        fields = [
            name
            for _, name, _, _ in string.Formatter().parse(value)
            if name is not None
        ]
    except ValueError as err:
        errors.append(f"discovery.{key}: Invalid format string: {err}")
        return
    bad = [name for name in fields if name and not name.isdigit()]
    if bad:
        errors.append(
            f"discovery.{key}: Invalid format string: capture groups are "
            f"numbered, so use {{0}}, {{1}}, ... rather than {{{bad[0]}}}"
        )

fetch

fetch(
    url: str,
    *,
    what: str,
    headers: dict[str, str] | None = None,
    hosts: set[str] | None = None
) -> requests.Response

Fetches a URL for a strategy and checks the response succeeded.

Parameters:

Name Type Description Default
url str

The URL to fetch.

required
what str

What is being fetched, for messages ("page", "API").

required
headers dict[str, str] | None

Request headers, secrets already expanded.

None
hosts set[str] | None

The hosts a redirect may go to when the headers carry a secret, from bound_hosts; None follows redirects freely.

None

Returns:

Type Description
Response

The successful response.

Raises:

Type Description
NetworkError

On transport failure, a redirect off the bound hosts, or a status that is not success.

Source code in napt/discovery/fields.py
def fetch(
    url: str,
    *,
    what: str,
    headers: dict[str, str] | None = None,
    hosts: set[str] | None = None,
) -> requests.Response:
    """Fetches a URL for a strategy and checks the response succeeded.

    Args:
        url: The URL to fetch.
        what: What is being fetched, for messages (``"page"``, ``"API"``).
        headers: Request headers, secrets already expanded.
        hosts: The hosts a redirect may go to when the headers carry a
            secret, from [bound_hosts][napt.secrets.bound_hosts]; None
            follows redirects freely.

    Returns:
        The successful response.

    Raises:
        NetworkError: On transport failure, a redirect off the bound hosts,
            or a status that is not success.
    """
    try:
        with make_session() as session:
            return _get(session, url, what, headers, hosts, stream=False)
    except requests.RequestException as err:
        raise NetworkError(f"Failed to fetch {what}: {err}") from err

fetch_text

fetch_text(
    url: str,
    *,
    what: str,
    max_bytes: int,
    headers: dict[str, str] | None = None,
    hosts: set[str] | None = None
) -> str

Fetches a text document for a strategy, refusing one over a size cap.

The body is read in pieces and the download stops as soon as it passes max_bytes, so a URL that points at a large file is refused without downloading it. A Content-Length header over the cap is refused before any of the body is read.

Parameters:

Name Type Description Default
url str

The URL to fetch.

required
what str

What is being fetched, for messages ("page").

required
max_bytes int

The largest body to accept.

required
headers dict[str, str] | None

Request headers, secrets already expanded.

None
hosts set[str] | None

The hosts a redirect may go to when the headers carry a secret, from bound_hosts; None follows redirects freely.

None

Returns:

Type Description
str

The document, decoded with the charset the response declares (UTF-8 when it declares none).

Raises:

Type Description
NetworkError

On transport failure, a redirect off the bound hosts, a status that is not success, or a body over max_bytes.

Source code in napt/discovery/fields.py
def fetch_text(
    url: str,
    *,
    what: str,
    max_bytes: int,
    headers: dict[str, str] | None = None,
    hosts: set[str] | None = None,
) -> str:
    """Fetches a text document for a strategy, refusing one over a size cap.

    The body is read in pieces and the download stops as soon as it passes
    ``max_bytes``, so a URL that points at a large file is refused without
    downloading it. A Content-Length header over the cap is refused before
    any of the body is read.

    Args:
        url: The URL to fetch.
        what: What is being fetched, for messages (``"page"``).
        max_bytes: The largest body to accept.
        headers: Request headers, secrets already expanded.
        hosts: The hosts a redirect may go to when the headers carry a
            secret, from [bound_hosts][napt.secrets.bound_hosts]; None
            follows redirects freely.

    Returns:
        The document, decoded with the charset the response declares
            (UTF-8 when it declares none).

    Raises:
        NetworkError: On transport failure, a redirect off the bound hosts,
            a status that is not success, or a body over ``max_bytes``.
    """
    too_large = NetworkError(
        f"The {what} at {url} is larger than {max_bytes} bytes, more than NAPT "
        f"reads for a download {what}. Check that the URL is the HTML {what} "
        "itself and not an installer file."
    )
    try:
        with make_session() as session:
            response = _get(session, url, what, headers, hosts, stream=True)
            declared = response.headers.get("Content-Length", "")
            if declared.isdigit() and int(declared) > max_bytes:
                raise too_large
            body = bytearray()
            for chunk in response.iter_content(chunk_size=64 * 1024):
                body.extend(chunk)
                if len(body) > max_bytes:
                    raise too_large
    except requests.RequestException as err:
        raise NetworkError(f"Failed to fetch {what}: {err}") from err
    try:
        return body.decode(response.encoding or "utf-8", errors="replace")
    except LookupError:
        # The server named a charset Python does not know.
        return body.decode("utf-8", errors="replace")

extract_version

extract_version(pattern_text: str, text: str, what: str) -> str

Reads the version a recipe pattern captures from a remote string.

Parameters:

Name Type Description Default
pattern_text str

The recipe's version_pattern, already validated.

required
text str

The string to search, already bounded.

required
what str

What the string is, for the message ("tag 'v1.2'").

required

Returns:

Type Description
str

Capture group 1 when the pattern has one, otherwise the whole

str

match.

Raises:

Type Description
ConfigError

If the pattern does not match, or a capture group took no part in the match.

Source code in napt/discovery/fields.py
def extract_version(pattern_text: str, text: str, what: str) -> str:
    """Reads the version a recipe pattern captures from a remote string.

    Args:
        pattern_text: The recipe's ``version_pattern``, already validated.
        text: The string to search, already bounded.
        what: What the string is, for the message (``"tag 'v1.2'"``).

    Returns:
        Capture group 1 when the pattern has one, otherwise the whole
        match.

    Raises:
        ConfigError: If the pattern does not match, or a capture group took
            no part in the match.
    """
    captured = first_capture(re.compile(pattern_text), text)
    if captured is None:
        raise ConfigError(f"Version pattern {pattern_text!r} did not match {what}")
    return captured

napt.discovery.registry

Explicit registry of discovery strategies.

Maps each discovery.strategy recipe value to the class implementing it. Dispatch is a plain table lookup: nothing registers itself at import time, and this module's imports are what pull in the strategy implementations.

Adding a strategy
  1. Implement DiscoveryStrategy in a new module under napt/discovery/, with FIELDS naming every recipe field it reads.
  2. Import the class here and add it to the table.
Note

url_download is intentionally absent from the table. It downloads the file before it can determine the version, which does not fit the version-first contract, so the discovery orchestrator dispatches to run_url_download directly.

get_strategy

get_strategy(name: str) -> DiscoveryStrategy

Returns a discovery strategy instance by name.

Strategies are stateless, so a fresh instance is created on every call.

Parameters:

Name Type Description Default
name str

Strategy name as written in recipe YAML under discovery.strategy. Case-sensitive.

required

Returns:

Type Description
DiscoveryStrategy

New instance of the requested strategy.

Raises:

Type Description
ConfigError

If the name is not in the registry. The message lists the available strategies for troubleshooting.

Source code in napt/discovery/registry.py
def get_strategy(name: str) -> DiscoveryStrategy:
    """Returns a discovery strategy instance by name.

    Strategies are stateless, so a fresh instance is created on every
    call.

    Args:
        name: Strategy name as written in recipe YAML under
            ``discovery.strategy``. Case-sensitive.

    Returns:
        New instance of the requested strategy.

    Raises:
        ConfigError: If the name is not in the registry. The message
            lists the available strategies for troubleshooting.

    """
    strategy_class = _STRATEGIES.get(name)
    if strategy_class is None:
        available = ", ".join(sorted([*_STRATEGIES, "url_download"]))
        raise ConfigError(
            f"Unknown discovery strategy: {name!r}. Available: {available}"
        )
    return strategy_class()

napt.discovery.resolve

Turns what a strategy found into an installer on disk.

Every discovery flow ends here. A strategy produces a download URL and, for the version-first strategies, the version it believes that URL serves. This module downloads the file, reads the version out of it when the installer can report one (MSI ProductVersion, MSIX Identity.Version), and files it under downloads/<id>/<version>/. The installer's own version is the one recorded, because it is what the detection and requirements scripts compare against on a device; the version a page or API reported is only the trigger that caused the download.

Skipping Downloads

Each app has one sidecar file, downloads/<id>/.download.json, recording what was last resolved: the trigger (the URL and, when the strategy supplied one, the version it reported), the server's ETag and Last-Modified, and the installer's version, name, and hash. The next run compares its trigger against that record:

  • A version-first strategy that reports the same version as last time from the same link reuses the installer without a request, provided that version and the installer's own agree as a device would compare them (4.41.106 and 4.41.106.0 do). The link is compared without its query string, where some vendor pages put a token that changes on every visit. When the version agrees but the link changed (a switched asset, a re-published release), or when the version and the installer's own disagree (a page updated before the file behind it, or a pattern capturing the wrong value), the report cannot vouch that nothing changed: the run asks the server instead, as url_download does.
  • url_download has no version to compare, so it sends the ETag / Last-Modified back as a conditional request and reuses the installer when the server answers HTTP 304, or answers 200 with the same validator (a server that ignores conditional requests; the body is not read).

The sidecar is a hint, not a record. Anything wrong with it, including an installer on disk that no longer matches the recorded hash, means one full download, never an error, and it is written only after the installer is in place.

Filing

A download lands in a per-run folder (downloads/<id>/.incoming-*) until its version is known, so two runs for one app never touch each other's partial file; a folder a crashed run left behind is removed once it is a day old. A file already filed under the same version with different bytes (a vendor re-releasing a version under one filename) is kept beside the new one under a hash-suffixed name, because the published release may have been built from it and napt build selects the installer by hash.

resolve_installer

resolve_installer(
    url: str,
    app_dir: Path,
    *,
    source: str,
    discovered_version: str | None = None
) -> StrategyResult

Resolves a strategy's finding to an installer on disk.

Reuses the app's last download when the sidecar shows the trigger is unchanged (see the module description); otherwise downloads the file, reads its version, and files it under that version.

Parameters:

Name Type Description Default
url str

URL the installer is served from.

required
app_dir Path

The app's download directory (downloads/<id>).

required
source str

Name of the strategy, recorded as the version source when the installer cannot report its own version.

required
discovered_version str | None

Version the strategy reported for url, or None for url_download, which learns the version from the file.

None

Returns:

Type Description
StrategyResult

Resolved version, its source, file path, and SHA-256 hash.

Raises:

Type Description
ConfigError

If the file's version cannot be used as a folder name, or if url_download fetched a file that cannot report a version.

NetworkError

On download failures.

PackagingError

If the installer's version cannot be read.

Source code in napt/discovery/resolve.py
def resolve_installer(
    url: str,
    app_dir: Path,
    *,
    source: str,
    discovered_version: str | None = None,
) -> StrategyResult:
    """Resolves a strategy's finding to an installer on disk.

    Reuses the app's last download when the sidecar shows the trigger is
    unchanged (see the module description); otherwise downloads the file,
    reads its version, and files it under that version.

    Args:
        url: URL the installer is served from.
        app_dir: The app's download directory (``downloads/<id>``).
        source: Name of the strategy, recorded as the version source when
            the installer cannot report its own version.
        discovered_version: Version the strategy reported for ``url``, or
            None for ``url_download``, which learns the version from the
            file.

    Returns:
        Resolved version, its source, file path, and SHA-256 hash.

    Raises:
        ConfigError: If the file's version cannot be used as a folder
            name, or if ``url_download`` fetched a file that cannot report
            a version.
        NetworkError: On download failures.
        PackagingError: If the installer's version cannot be read.

    """
    logger = get_global_logger()
    previous = _load_sidecar(app_dir)

    try:
        if discovered_version is not None:
            # The reported version and the link are the trigger. The link
            # is compared without its query string, where some vendor
            # pages put a token that changes on every visit.
            if previous is None or previous.discovered_version != discovered_version:
                return _download_and_file(url, app_dir, source, discovered_version)
            if _without_query(url) != _without_query(previous.url):
                # Same version behind a different link: a switched asset
                # or a re-published release. The version cannot vouch for
                # the file, so ask the server.
                logger.info(
                    "DISCOVERY",
                    f"Download link changed at version {discovered_version}; "
                    "checking the server",
                )
                return _refresh(previous, url, app_dir, source, discovered_version)
            if compare_versions(discovered_version, previous.version) == 0:
                logger.info(
                    "DISCOVERY",
                    f"Version {discovered_version} already downloaded, "
                    f"using {previous.file_path}",
                )
                return _reuse(previous, url, source)
            # The reported version was already wrong about this file once,
            # so it cannot vouch that nothing changed. Ask the server.
            _warn_mismatch(source, discovered_version, previous.version)
            return _refresh(previous, url, app_dir, source, discovered_version)

        if previous is None or previous.url != url:
            return _download_and_file(url, app_dir, source, None)
        return _refresh(previous, url, app_dir, source, None)
    except OSError as err:
        # The staging folder or the file itself could not be written.
        raise NetworkError(f"Failed to download {url}: {err}") from err

napt.discovery.url_download

url_download discovery flow.

This module is intentionally not a DiscoveryStrategy. The strategies in napt.discovery.base produce a RemoteVersion from configuration alone (version-first). url_download cannot do that: it has no remote endpoint to query for the version, so it must download the installer and read the version from the file itself. The discovery orchestrator special-cases strategy: url_download and dispatches to run_url_download directly.

The download, the version read, and the reuse of an unchanged file all happen in napt.discovery.resolve, shared with the version-first strategies. With no version to compare, this flow relies on the server's ETag / Last-Modified to learn whether the file changed.

Supported File Types
  • .msi: version is read from the MSI ProductVersion property.
  • .msix: version is read from the package's Identity element.
  • Other extensions raise ConfigError. For those installers, use a version-first strategy.
Recipe Example
discovery:
  strategy: url_download
  url: "https://vendor.example.com/installer.msi"

The recipe reference defines each field.

run_url_download

run_url_download(
    app_config: dict[str, Any], output_dir: Path
) -> StrategyResult

Downloads a fixed URL and reads the version from the resulting file.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged recipe configuration dict containing discovery.url and id, already validated.

required
output_dir Path

Base directory to download into. The file lands in output_dir / app_id / version.

required

Returns:

Type Description
StrategyResult

Resolved version, file path, and SHA-256 hash.

Raises:

Type Description
ConfigError

If the downloaded file is not an MSI or MSIX, or its version cannot name a folder.

NetworkError

On download failures.

PackagingError

If the installer's version cannot be read.

Source code in napt/discovery/url_download.py
def run_url_download(
    app_config: dict[str, Any],
    output_dir: Path,
) -> StrategyResult:
    """Downloads a fixed URL and reads the version from the resulting file.

    Args:
        app_config: Merged recipe configuration dict containing
            ``discovery.url`` and ``id``, already validated.
        output_dir: Base directory to download into. The file lands
            in ``output_dir / app_id / version``.

    Returns:
        Resolved version, file path, and SHA-256 hash.

    Raises:
        ConfigError: If the downloaded file is not an MSI or MSIX, or its
            version cannot name a folder.
        NetworkError: On download failures.
        PackagingError: If the installer's version cannot be read.

    """
    logger = get_global_logger()
    url = app_config["discovery"]["url"]

    logger.verbose("DISCOVERY", "Strategy: url_download (file-first)")
    logger.verbose("DISCOVERY", f"Source URL: {url}")

    return resolve_installer(url, output_dir / app_config["id"], source="url_download")

validate_url_download_config

validate_url_download_config(app_config: dict[str, Any]) -> list[str]

Validates url_download configuration fields.

Called by napt.validation.validate_config to compose the url_download field rules into the overall recipe validation.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged recipe configuration dict.

required

Returns:

Type Description
list[str]

Human-readable error messages. Empty when configuration is valid.

Source code in napt/discovery/url_download.py
def validate_url_download_config(app_config: dict[str, Any]) -> list[str]:
    """Validates url_download configuration fields.

    Called by [napt.validation.validate_config][] to compose the
    url_download field rules into the overall recipe validation.

    Args:
        app_config: Merged recipe configuration dict.

    Returns:
        Human-readable error messages. Empty when configuration is valid.

    """
    errors: list[str] = []
    require_str(app_config.get("discovery", {}), "url", errors)
    return errors

napt.discovery.web_scrape

Web scraping discovery strategy.

Fetches a vendor download page, locates a download link, and extracts the version from that link's URL. Use this when a vendor has neither a JSON API nor a GitHub releases feed.

Recipe Example (CSS selector, recommended):

discovery:
  strategy: web_scrape
  page_url: "https://www.7-zip.org/download.html"
  link_selector: 'a[href$="-x64.msi"]'
  version_pattern: "7z(\\d{2})(\\d{2})-x64"
  version_format: "{0}.{1}"     # transforms ("25", "01") -> "25.01"

The recipe reference defines each field, including the link_pattern regex fallback.

Finding a CSS Selector
  1. Open the download page in Chrome / Edge / Firefox.
  2. Right-click the download link -> Inspect.
  3. Right-click the highlighted element -> Copy -> Copy selector.
  4. Simplify the result. Common shapes:
    • a[href$=".msi"] (links ending in .msi)
    • a[href*="x64"] (links containing "x64")
    • a.download (links with class="download")
Note

The selector / pattern is expected to match exactly one link; the first match is used. Relative URLs in the page are resolved against page_url.

WebScrapeStrategy

Discovery strategy for scraping vendor download pages.

Source code in napt/discovery/web_scrape.py
class WebScrapeStrategy:
    """Discovery strategy for scraping vendor download pages."""

    FIELDS: ClassVar[frozenset[str]] = frozenset(
        {
            "page_url",
            "link_selector",
            "link_pattern",
            "version_pattern",
            "version_format",
        }
    )

    def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
        r"""Discovers version and download URL by scraping a vendor page.

        Fetches ``discovery.page_url``, locates a download link with
        either ``link_selector`` (CSS) or ``link_pattern`` (regex),
        and extracts the version from the matched link using
        ``version_pattern``.

        Args:
            app_config: Merged and validated recipe configuration dict
                containing ``discovery.page_url``, one of
                ``discovery.link_selector`` or ``discovery.link_pattern``,
                and ``discovery.version_pattern``.

        Returns:
            Discovered version, the matched link's URL, and
            ``"web_scrape"`` as the source identifier.

        Raises:
            ConfigError: When a selector or pattern matches nothing, or
                ``version_format`` cannot take the captured groups.
            NetworkError: On page fetch failure, a page larger than NAPT
                parses, or a matched link too long to match a pattern on.

        """
        logger = get_global_logger()
        source = app_config["discovery"]
        page_url: str = source["page_url"]
        link_selector = source.get("link_selector")
        link_pattern = source.get("link_pattern")
        version_pattern: str = source["version_pattern"]
        version_format: str = source.get("version_format", _DEFAULT_VERSION_FORMAT)

        logger.verbose("DISCOVERY", "Strategy: web_scrape (version-first)")
        logger.verbose("DISCOVERY", f"Page URL: {page_url}")
        if link_selector:
            logger.verbose("DISCOVERY", f"Link selector (CSS): {link_selector}")
        if link_pattern:
            logger.verbose("DISCOVERY", f"Link pattern (regex): {link_pattern}")
        logger.verbose("DISCOVERY", f"Version pattern: {version_pattern}")

        logger.verbose("DISCOVERY", f"Fetching page: {page_url}")
        html_content = fetch_text(page_url, what="page", max_bytes=_MAX_PAGE_BYTES)
        logger.verbose("DISCOVERY", f"Page fetched ({len(html_content)} characters)")

        if link_selector:
            soup = BeautifulSoup(html_content, "html.parser")
            element = soup.select_one(link_selector)
            if not element:
                raise ConfigError(
                    f"CSS selector {link_selector!r} did not match any elements on page"
                )
            href = element.get("href")
            if not isinstance(href, str) or not href:
                raise ConfigError(
                    f"Element matched by {link_selector!r} has no href attribute"
                )
            logger.verbose("DISCOVERY", f"Found link via CSS: {href}")
        else:
            href = first_capture(re.compile(link_pattern), html_content)
            if href is None:
                raise ConfigError(
                    f"Regex pattern {link_pattern!r} did not match anything on page"
                )
            logger.verbose("DISCOVERY", f"Found link via regex: {href}")

        download_url = bounded(urljoin(page_url, href), "The matched download link")
        logger.verbose("DISCOVERY", f"Download URL: {download_url}")

        match = re.compile(version_pattern).search(download_url)
        if not match:
            raise ConfigError(
                f"Version pattern {version_pattern!r} did not match "
                f"URL {download_url!r}"
            )

        # A group that took no part in the match would format as the text
        # "None", so it counts as no match.
        groups = match.groups()
        if any(group is None for group in groups):
            raise ConfigError(
                f"Version pattern {version_pattern!r} did not match "
                f"URL {download_url!r}: a capture group matched nothing"
            )

        if not groups:
            version_str = match.group(0)
        else:
            try:
                version_str = version_format.format(*groups)
            except (IndexError, KeyError, ValueError) as err:
                raise ConfigError(
                    f"version_format {version_format!r} failed with "
                    f"groups {groups}: {err}"
                ) from err

        logger.verbose("DISCOVERY", f"Extracted version: {version_str}")

        return RemoteVersion(
            version=version_str,
            download_url=download_url,
            source="web_scrape",
        )

    def validate_config(self, app_config: dict[str, Any]) -> list[str]:
        """Validate web_scrape strategy configuration.

        Checks for required fields and correct types without making network calls.

        Args:
            app_config: The app configuration from the recipe.

        Returns:
            List of error messages (empty if valid).

        """
        errors: list[str] = []
        source = app_config.get("discovery", {})

        require_str(source, "page_url", errors)

        if "link_selector" not in source and "link_pattern" not in source:
            errors.append(
                "discovery: Missing required field: link_selector or link_pattern"
            )
        elif "link_selector" in source and "link_pattern" in source:
            errors.append("discovery: Set link_selector or link_pattern, not both")

        link_selector = optional_str(source, "link_selector", errors)
        if link_selector is not None:
            try:
                BeautifulSoup("<html></html>", "html.parser").select_one(link_selector)
            except Exception as err:
                errors.append(f"discovery.link_selector: Invalid CSS selector: {err}")

        link_pattern = optional_str(source, "link_pattern", errors)
        if link_pattern is not None:
            check_regex(link_pattern, "link_pattern", errors)

        version_pattern = require_str(source, "version_pattern", errors)
        if version_pattern is not None:
            check_regex(version_pattern, "version_pattern", errors)

        version_format = optional_str(source, "version_format", errors)
        if version_format is not None:
            check_format(version_format, "version_format", errors)

        return errors

discover

discover(app_config: dict[str, Any]) -> RemoteVersion

Discovers version and download URL by scraping a vendor page.

Fetches discovery.page_url, locates a download link with either link_selector (CSS) or link_pattern (regex), and extracts the version from the matched link using version_pattern.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged and validated recipe configuration dict containing discovery.page_url, one of discovery.link_selector or discovery.link_pattern, and discovery.version_pattern.

required

Returns:

Type Description
RemoteVersion

Discovered version, the matched link's URL, and

RemoteVersion

"web_scrape" as the source identifier.

Raises:

Type Description
ConfigError

When a selector or pattern matches nothing, or version_format cannot take the captured groups.

NetworkError

On page fetch failure, a page larger than NAPT parses, or a matched link too long to match a pattern on.

Source code in napt/discovery/web_scrape.py
def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
    r"""Discovers version and download URL by scraping a vendor page.

    Fetches ``discovery.page_url``, locates a download link with
    either ``link_selector`` (CSS) or ``link_pattern`` (regex),
    and extracts the version from the matched link using
    ``version_pattern``.

    Args:
        app_config: Merged and validated recipe configuration dict
            containing ``discovery.page_url``, one of
            ``discovery.link_selector`` or ``discovery.link_pattern``,
            and ``discovery.version_pattern``.

    Returns:
        Discovered version, the matched link's URL, and
        ``"web_scrape"`` as the source identifier.

    Raises:
        ConfigError: When a selector or pattern matches nothing, or
            ``version_format`` cannot take the captured groups.
        NetworkError: On page fetch failure, a page larger than NAPT
            parses, or a matched link too long to match a pattern on.

    """
    logger = get_global_logger()
    source = app_config["discovery"]
    page_url: str = source["page_url"]
    link_selector = source.get("link_selector")
    link_pattern = source.get("link_pattern")
    version_pattern: str = source["version_pattern"]
    version_format: str = source.get("version_format", _DEFAULT_VERSION_FORMAT)

    logger.verbose("DISCOVERY", "Strategy: web_scrape (version-first)")
    logger.verbose("DISCOVERY", f"Page URL: {page_url}")
    if link_selector:
        logger.verbose("DISCOVERY", f"Link selector (CSS): {link_selector}")
    if link_pattern:
        logger.verbose("DISCOVERY", f"Link pattern (regex): {link_pattern}")
    logger.verbose("DISCOVERY", f"Version pattern: {version_pattern}")

    logger.verbose("DISCOVERY", f"Fetching page: {page_url}")
    html_content = fetch_text(page_url, what="page", max_bytes=_MAX_PAGE_BYTES)
    logger.verbose("DISCOVERY", f"Page fetched ({len(html_content)} characters)")

    if link_selector:
        soup = BeautifulSoup(html_content, "html.parser")
        element = soup.select_one(link_selector)
        if not element:
            raise ConfigError(
                f"CSS selector {link_selector!r} did not match any elements on page"
            )
        href = element.get("href")
        if not isinstance(href, str) or not href:
            raise ConfigError(
                f"Element matched by {link_selector!r} has no href attribute"
            )
        logger.verbose("DISCOVERY", f"Found link via CSS: {href}")
    else:
        href = first_capture(re.compile(link_pattern), html_content)
        if href is None:
            raise ConfigError(
                f"Regex pattern {link_pattern!r} did not match anything on page"
            )
        logger.verbose("DISCOVERY", f"Found link via regex: {href}")

    download_url = bounded(urljoin(page_url, href), "The matched download link")
    logger.verbose("DISCOVERY", f"Download URL: {download_url}")

    match = re.compile(version_pattern).search(download_url)
    if not match:
        raise ConfigError(
            f"Version pattern {version_pattern!r} did not match "
            f"URL {download_url!r}"
        )

    # A group that took no part in the match would format as the text
    # "None", so it counts as no match.
    groups = match.groups()
    if any(group is None for group in groups):
        raise ConfigError(
            f"Version pattern {version_pattern!r} did not match "
            f"URL {download_url!r}: a capture group matched nothing"
        )

    if not groups:
        version_str = match.group(0)
    else:
        try:
            version_str = version_format.format(*groups)
        except (IndexError, KeyError, ValueError) as err:
            raise ConfigError(
                f"version_format {version_format!r} failed with "
                f"groups {groups}: {err}"
            ) from err

    logger.verbose("DISCOVERY", f"Extracted version: {version_str}")

    return RemoteVersion(
        version=version_str,
        download_url=download_url,
        source="web_scrape",
    )

validate_config

validate_config(app_config: dict[str, Any]) -> list[str]

Validate web_scrape strategy configuration.

Checks for required fields and correct types without making network calls.

Parameters:

Name Type Description Default
app_config dict[str, Any]

The app configuration from the recipe.

required

Returns:

Type Description
list[str]

List of error messages (empty if valid).

Source code in napt/discovery/web_scrape.py
def validate_config(self, app_config: dict[str, Any]) -> list[str]:
    """Validate web_scrape strategy configuration.

    Checks for required fields and correct types without making network calls.

    Args:
        app_config: The app configuration from the recipe.

    Returns:
        List of error messages (empty if valid).

    """
    errors: list[str] = []
    source = app_config.get("discovery", {})

    require_str(source, "page_url", errors)

    if "link_selector" not in source and "link_pattern" not in source:
        errors.append(
            "discovery: Missing required field: link_selector or link_pattern"
        )
    elif "link_selector" in source and "link_pattern" in source:
        errors.append("discovery: Set link_selector or link_pattern, not both")

    link_selector = optional_str(source, "link_selector", errors)
    if link_selector is not None:
        try:
            BeautifulSoup("<html></html>", "html.parser").select_one(link_selector)
        except Exception as err:
            errors.append(f"discovery.link_selector: Invalid CSS selector: {err}")

    link_pattern = optional_str(source, "link_pattern", errors)
    if link_pattern is not None:
        check_regex(link_pattern, "link_pattern", errors)

    version_pattern = require_str(source, "version_pattern", errors)
    if version_pattern is not None:
        check_regex(version_pattern, "version_pattern", errors)

    version_format = optional_str(source, "version_format", errors)
    if version_format is not None:
        check_format(version_format, "version_format", errors)

    return errors

napt.discovery.api_github

GitHub releases discovery strategy.

Queries the GitHub releases API for the latest tag and the download URL of a matching asset. The version comes from the release tag (parsed with a regex); the download URL comes from the first asset whose filename matches asset_pattern.

Recipe Example
discovery:
  strategy: api_github
  repo: "git-for-windows/git"            # required, "owner/name"
  asset_pattern: "Git-.*-64-bit\\.exe$"  # required, regex on asset filename
  version_pattern: "v?([0-9.]+)"         # optional, default strips "v"
  token: "${GITHUB_TOKEN}"               # optional

The recipe reference defines each field.

Note

The request goes to the latest-release endpoint, which never returns a pre-release or a draft. If no asset matches, discovery raises an error rather than walking back through history. ${VAR} in token is replaced with that environment variable, provided defaults/org.yaml declares it under secrets and binds it to api.github.com (see napt.secrets); an undeclared or unset variable stops discovery.

ApiGithubStrategy

Discovery strategy for GitHub releases.

Source code in napt/discovery/api_github.py
class ApiGithubStrategy:
    """Discovery strategy for GitHub releases."""

    FIELDS: ClassVar[frozenset[str]] = frozenset(
        {"repo", "asset_pattern", "version_pattern", "token"}
    )

    def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
        r"""Discovers the latest GitHub release version and asset download URL.

        Queries the GitHub releases API for the latest release of the
        configured repository. Extracts the version from the release tag
        (via ``version_pattern``) and the download URL from the first
        asset matching ``asset_pattern``.

        Args:
            app_config: Merged and validated recipe configuration dict
                containing ``discovery.repo`` and ``discovery.asset_pattern``,
                plus optional ``version_pattern`` and ``token`` fields.

        Returns:
            Latest version, the matched asset's download URL, and
            ``"api_github"`` as the source identifier.

        Raises:
            ConfigError: On a token secret org.yaml does not declare, binds
                to another host, or that is not set, or when patterns do
                not match the release.
            NetworkError: On API failure, missing assets, or a tag or
                asset name too long to match a pattern on.

        """
        logger = get_global_logger()
        source = app_config["discovery"]
        repo: str = source["repo"]
        asset_pattern: str = source["asset_pattern"]
        version_pattern: str = source.get("version_pattern", _DEFAULT_VERSION_PATTERN)
        raw_token = source.get("token")

        api_url = f"{API_BASE}/repos/{repo}/releases/latest"

        # Expand ${VAR} in the token; an undeclared or unset variable stops
        # discovery rather than sending the request unauthenticated. A
        # literal token is bound to api.github.com like a declared one, so
        # no redirect carries it elsewhere.
        token = None
        hosts: set[str] | None = None
        if raw_token:
            token = expand_secrets(
                app_config, str(raw_token), api_url, "discovery.token"
            )
            hosts = bound_hosts(app_config, [str(raw_token)])
            if hosts is None:
                hosts = {API_HOST}
            logger.verbose("DISCOVERY", "Using authenticated API request")

        logger.verbose("DISCOVERY", "Strategy: api_github (version-first)")
        logger.verbose("DISCOVERY", f"Repository: {repo}")
        logger.verbose("DISCOVERY", f"Version pattern: {version_pattern}")
        logger.verbose("DISCOVERY", f"Asset pattern: {asset_pattern}")

        with make_session() as session:
            release_data = latest_release(session, repo, token=token, hosts=hosts)

        tag_name = bounded(release_tag(release_data), "The release tag")
        logger.verbose("DISCOVERY", f"Release tag: {tag_name}")
        version_str = extract_version(version_pattern, tag_name, f"tag {tag_name!r}")
        logger.verbose("DISCOVERY", f"Extracted version: {version_str}")

        assets = release_data.get("assets") or []
        if not assets:
            raise NetworkError(
                f"Release {tag_name} has no assets. "
                f"Check if assets were uploaded to the release."
            )
        logger.verbose("DISCOVERY", f"Release has {len(assets)} asset(s)")

        pattern = re.compile(asset_pattern)
        matched_asset = find_asset(
            release_data,
            lambda name: pattern.search(bounded(name, "An asset name")) is not None,
        )
        if matched_asset is None:
            raise ConfigError(
                f"No assets matched pattern {asset_pattern!r}. "
                f"Available assets: {', '.join(asset_names(release_data))}"
            )
        logger.verbose("DISCOVERY", f"Matched asset: {matched_asset.get('name')}")

        download_url = asset_url(matched_asset)
        logger.verbose("DISCOVERY", f"Download URL: {download_url}")

        return RemoteVersion(
            version=version_str,
            download_url=download_url,
            source="api_github",
        )

    def validate_config(self, app_config: dict[str, Any]) -> list[str]:
        """Validate api_github strategy configuration.

        Checks for required fields and correct types without making network calls.

        Args:
            app_config: The app configuration from the recipe.

        Returns:
            List of error messages (empty if valid).

        """
        errors: list[str] = []
        source = app_config.get("discovery", {})

        repo = require_str(source, "repo", errors)
        if repo is not None and repo.count("/") != 1:
            errors.append(
                "discovery.repo: Must be owner/repository (for example git/git)"
            )

        asset_pattern = require_str(source, "asset_pattern", errors)
        if asset_pattern is not None:
            check_regex(asset_pattern, "asset_pattern", errors)

        version_pattern = optional_str(source, "version_pattern", errors)
        if version_pattern is not None:
            check_regex(version_pattern, "version_pattern", errors)

        token = source.get("token")
        if token is not None:
            if not isinstance(token, str):
                errors.append("discovery.token: Must be a string")
            else:
                errors.extend(
                    check_secret_use(
                        app_config,
                        token,
                        f"https://{API_HOST}/",
                        "discovery.token",
                    )
                )

        return errors

discover

discover(app_config: dict[str, Any]) -> RemoteVersion

Discovers the latest GitHub release version and asset download URL.

Queries the GitHub releases API for the latest release of the configured repository. Extracts the version from the release tag (via version_pattern) and the download URL from the first asset matching asset_pattern.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged and validated recipe configuration dict containing discovery.repo and discovery.asset_pattern, plus optional version_pattern and token fields.

required

Returns:

Type Description
RemoteVersion

Latest version, the matched asset's download URL, and

RemoteVersion

"api_github" as the source identifier.

Raises:

Type Description
ConfigError

On a token secret org.yaml does not declare, binds to another host, or that is not set, or when patterns do not match the release.

NetworkError

On API failure, missing assets, or a tag or asset name too long to match a pattern on.

Source code in napt/discovery/api_github.py
def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
    r"""Discovers the latest GitHub release version and asset download URL.

    Queries the GitHub releases API for the latest release of the
    configured repository. Extracts the version from the release tag
    (via ``version_pattern``) and the download URL from the first
    asset matching ``asset_pattern``.

    Args:
        app_config: Merged and validated recipe configuration dict
            containing ``discovery.repo`` and ``discovery.asset_pattern``,
            plus optional ``version_pattern`` and ``token`` fields.

    Returns:
        Latest version, the matched asset's download URL, and
        ``"api_github"`` as the source identifier.

    Raises:
        ConfigError: On a token secret org.yaml does not declare, binds
            to another host, or that is not set, or when patterns do
            not match the release.
        NetworkError: On API failure, missing assets, or a tag or
            asset name too long to match a pattern on.

    """
    logger = get_global_logger()
    source = app_config["discovery"]
    repo: str = source["repo"]
    asset_pattern: str = source["asset_pattern"]
    version_pattern: str = source.get("version_pattern", _DEFAULT_VERSION_PATTERN)
    raw_token = source.get("token")

    api_url = f"{API_BASE}/repos/{repo}/releases/latest"

    # Expand ${VAR} in the token; an undeclared or unset variable stops
    # discovery rather than sending the request unauthenticated. A
    # literal token is bound to api.github.com like a declared one, so
    # no redirect carries it elsewhere.
    token = None
    hosts: set[str] | None = None
    if raw_token:
        token = expand_secrets(
            app_config, str(raw_token), api_url, "discovery.token"
        )
        hosts = bound_hosts(app_config, [str(raw_token)])
        if hosts is None:
            hosts = {API_HOST}
        logger.verbose("DISCOVERY", "Using authenticated API request")

    logger.verbose("DISCOVERY", "Strategy: api_github (version-first)")
    logger.verbose("DISCOVERY", f"Repository: {repo}")
    logger.verbose("DISCOVERY", f"Version pattern: {version_pattern}")
    logger.verbose("DISCOVERY", f"Asset pattern: {asset_pattern}")

    with make_session() as session:
        release_data = latest_release(session, repo, token=token, hosts=hosts)

    tag_name = bounded(release_tag(release_data), "The release tag")
    logger.verbose("DISCOVERY", f"Release tag: {tag_name}")
    version_str = extract_version(version_pattern, tag_name, f"tag {tag_name!r}")
    logger.verbose("DISCOVERY", f"Extracted version: {version_str}")

    assets = release_data.get("assets") or []
    if not assets:
        raise NetworkError(
            f"Release {tag_name} has no assets. "
            f"Check if assets were uploaded to the release."
        )
    logger.verbose("DISCOVERY", f"Release has {len(assets)} asset(s)")

    pattern = re.compile(asset_pattern)
    matched_asset = find_asset(
        release_data,
        lambda name: pattern.search(bounded(name, "An asset name")) is not None,
    )
    if matched_asset is None:
        raise ConfigError(
            f"No assets matched pattern {asset_pattern!r}. "
            f"Available assets: {', '.join(asset_names(release_data))}"
        )
    logger.verbose("DISCOVERY", f"Matched asset: {matched_asset.get('name')}")

    download_url = asset_url(matched_asset)
    logger.verbose("DISCOVERY", f"Download URL: {download_url}")

    return RemoteVersion(
        version=version_str,
        download_url=download_url,
        source="api_github",
    )

validate_config

validate_config(app_config: dict[str, Any]) -> list[str]

Validate api_github strategy configuration.

Checks for required fields and correct types without making network calls.

Parameters:

Name Type Description Default
app_config dict[str, Any]

The app configuration from the recipe.

required

Returns:

Type Description
list[str]

List of error messages (empty if valid).

Source code in napt/discovery/api_github.py
def validate_config(self, app_config: dict[str, Any]) -> list[str]:
    """Validate api_github strategy configuration.

    Checks for required fields and correct types without making network calls.

    Args:
        app_config: The app configuration from the recipe.

    Returns:
        List of error messages (empty if valid).

    """
    errors: list[str] = []
    source = app_config.get("discovery", {})

    repo = require_str(source, "repo", errors)
    if repo is not None and repo.count("/") != 1:
        errors.append(
            "discovery.repo: Must be owner/repository (for example git/git)"
        )

    asset_pattern = require_str(source, "asset_pattern", errors)
    if asset_pattern is not None:
        check_regex(asset_pattern, "asset_pattern", errors)

    version_pattern = optional_str(source, "version_pattern", errors)
    if version_pattern is not None:
        check_regex(version_pattern, "version_pattern", errors)

    token = source.get("token")
    if token is not None:
        if not isinstance(token, str):
            errors.append("discovery.token: Must be a string")
        else:
            errors.extend(
                check_secret_use(
                    app_config,
                    token,
                    f"https://{API_HOST}/",
                    "discovery.token",
                )
            )

    return errors

napt.discovery.api_json

JSON API discovery strategy.

Queries a JSON API endpoint for the latest version and download URL. Both fields are read from the response with dotted paths.

Recipe Example
discovery:
  strategy: api_json
  api_url: "https://vendor.example.com/api/latest"  # required
  version_path: "version"                           # required, dotted path
  download_url_path: "builds[0].url"                # required, dotted path
  version_pattern: "v?([0-9.]+)"                    # optional, regex
  headers:                                          # optional
    Authorization: "Bearer ${API_TOKEN}"            # declared in org.yaml
    Accept: "application/json"

The recipe reference defines each field.

Note

A path is keys separated by dots, with [n] for a list index: data.version, builds[0].url. ${VAR} anywhere in a header value is replaced with that environment variable, provided defaults/org.yaml declares it under secrets and binds it to the API host; see napt.secrets. An undeclared or unset variable stops discovery before the request is sent.

ApiJsonStrategy

Discovery strategy for JSON API endpoints.

Source code in napt/discovery/api_json.py
class ApiJsonStrategy:
    """Discovery strategy for JSON API endpoints."""

    FIELDS: ClassVar[frozenset[str]] = frozenset(
        {"api_url", "version_path", "download_url_path", "version_pattern", "headers"}
    )

    def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
        """Discovers version and download URL from a JSON API endpoint.

        Sends a GET request to the configured ``api_url`` and reads the
        version and download URL at the configured paths.

        Args:
            app_config: Merged and validated recipe configuration dict
                containing ``discovery.api_url``, ``discovery.version_path``,
                and ``discovery.download_url_path``, plus optional
                ``version_pattern`` and ``headers`` fields.

        Returns:
            Discovered version, download URL, and ``"api_json"`` as
            the source identifier.

        Raises:
            ConfigError: On a header secret that org.yaml does not allow for
                the API host or that is not set, when a path does not match
                the response or finds the wrong kind of value, or when
                ``version_pattern`` does not match.
            NetworkError: On API request failure, a redirect that would
                carry a secret off its bound hosts, or a version value too
                long to match a pattern on.

        """
        logger = get_global_logger()
        source = app_config["discovery"]
        api_url: str = source["api_url"]
        version_path: str = source["version_path"]
        download_url_path: str = source["download_url_path"]
        headers = {str(k): str(v) for k, v in (source.get("headers") or {}).items()}

        logger.verbose("DISCOVERY", "Strategy: api_json (version-first)")
        logger.verbose("DISCOVERY", f"API URL: {api_url}")
        logger.verbose("DISCOVERY", f"Version path: {version_path}")
        logger.verbose("DISCOVERY", f"Download URL path: {download_url_path}")

        # Expand secrets in headers; a header org.yaml does not allow for
        # this host, or whose variable is unset, stops discovery here.
        expanded_headers = {
            name: expand_secrets(
                app_config, value, api_url, f"discovery.headers.{name}"
            )
            for name, value in headers.items()
        }
        hosts = bound_hosts(app_config, headers.values())

        logger.verbose("DISCOVERY", f"Calling API: GET {api_url}")
        response = fetch(api_url, what="API", headers=expanded_headers, hosts=hosts)
        logger.verbose("DISCOVERY", f"API response: {response.status_code} OK")

        try:
            json_data = response.json()
        except json.JSONDecodeError as err:
            raise NetworkError(
                f"Invalid JSON response from API. Response: {response.text[:200]}"
            ) from err

        logger.debug("DISCOVERY", f"JSON response: {json.dumps(json_data, indent=2)}")

        version_value = _lookup(json_data, version_path, "version_path")
        if not isinstance(version_value, (str, int, float)) or isinstance(
            version_value, bool
        ):
            raise ConfigError(
                f"discovery.version_path {version_path!r} found "
                f"{type(version_value).__name__} in the API response, not a "
                f"version"
            )
        version_str = bounded(str(version_value), "The API's version value")
        logger.verbose("DISCOVERY", f"Extracted version: {version_str}")

        version_pattern = source.get("version_pattern")
        if version_pattern is not None:
            logger.verbose("DISCOVERY", f"Version pattern: {version_pattern}")
            version_str = extract_version(
                version_pattern, version_str, f"the API's version value {version_str!r}"
            )
            logger.verbose("DISCOVERY", f"Version after pattern: {version_str}")

        download_url = _lookup(json_data, download_url_path, "download_url_path")
        if not isinstance(download_url, str) or not download_url:
            raise ConfigError(
                f"discovery.download_url_path {download_url_path!r} found "
                f"{type(download_url).__name__} in the API response, not a URL"
            )
        logger.verbose("DISCOVERY", f"Download URL: {download_url}")

        return RemoteVersion(
            version=version_str,
            download_url=download_url,
            source="api_json",
        )

    def validate_config(self, app_config: dict[str, Any]) -> list[str]:
        """Validate api_json strategy configuration.

        Checks for required fields and correct types without making network calls.

        Args:
            app_config: The app configuration from the recipe.

        Returns:
            List of error messages (empty if valid).

        """
        errors: list[str] = []
        source = app_config.get("discovery", {})

        api_url = require_str(source, "api_url", errors)
        for key in ("version_path", "download_url_path"):
            path = require_str(source, key, errors)
            if path is not None:
                _check_path(path, key, errors)

        headers = source.get("headers")
        if "headers" in source and not isinstance(headers, dict):
            errors.append("discovery.headers: Must be a dictionary")
        elif isinstance(headers, dict):
            for name, value in headers.items():
                field_path = f"discovery.headers.{name}"
                if not isinstance(value, str):
                    errors.append(f"{field_path}: Must be a string")
                    continue
                errors.extend(
                    check_secret_use(app_config, value, api_url or "", field_path)
                )

        version_pattern = optional_str(source, "version_pattern", errors)
        if version_pattern is not None:
            check_regex(version_pattern, "version_pattern", errors)

        return errors

discover

discover(app_config: dict[str, Any]) -> RemoteVersion

Discovers version and download URL from a JSON API endpoint.

Sends a GET request to the configured api_url and reads the version and download URL at the configured paths.

Parameters:

Name Type Description Default
app_config dict[str, Any]

Merged and validated recipe configuration dict containing discovery.api_url, discovery.version_path, and discovery.download_url_path, plus optional version_pattern and headers fields.

required

Returns:

Type Description
RemoteVersion

Discovered version, download URL, and "api_json" as

RemoteVersion

the source identifier.

Raises:

Type Description
ConfigError

On a header secret that org.yaml does not allow for the API host or that is not set, when a path does not match the response or finds the wrong kind of value, or when version_pattern does not match.

NetworkError

On API request failure, a redirect that would carry a secret off its bound hosts, or a version value too long to match a pattern on.

Source code in napt/discovery/api_json.py
def discover(self, app_config: dict[str, Any]) -> RemoteVersion:
    """Discovers version and download URL from a JSON API endpoint.

    Sends a GET request to the configured ``api_url`` and reads the
    version and download URL at the configured paths.

    Args:
        app_config: Merged and validated recipe configuration dict
            containing ``discovery.api_url``, ``discovery.version_path``,
            and ``discovery.download_url_path``, plus optional
            ``version_pattern`` and ``headers`` fields.

    Returns:
        Discovered version, download URL, and ``"api_json"`` as
        the source identifier.

    Raises:
        ConfigError: On a header secret that org.yaml does not allow for
            the API host or that is not set, when a path does not match
            the response or finds the wrong kind of value, or when
            ``version_pattern`` does not match.
        NetworkError: On API request failure, a redirect that would
            carry a secret off its bound hosts, or a version value too
            long to match a pattern on.

    """
    logger = get_global_logger()
    source = app_config["discovery"]
    api_url: str = source["api_url"]
    version_path: str = source["version_path"]
    download_url_path: str = source["download_url_path"]
    headers = {str(k): str(v) for k, v in (source.get("headers") or {}).items()}

    logger.verbose("DISCOVERY", "Strategy: api_json (version-first)")
    logger.verbose("DISCOVERY", f"API URL: {api_url}")
    logger.verbose("DISCOVERY", f"Version path: {version_path}")
    logger.verbose("DISCOVERY", f"Download URL path: {download_url_path}")

    # Expand secrets in headers; a header org.yaml does not allow for
    # this host, or whose variable is unset, stops discovery here.
    expanded_headers = {
        name: expand_secrets(
            app_config, value, api_url, f"discovery.headers.{name}"
        )
        for name, value in headers.items()
    }
    hosts = bound_hosts(app_config, headers.values())

    logger.verbose("DISCOVERY", f"Calling API: GET {api_url}")
    response = fetch(api_url, what="API", headers=expanded_headers, hosts=hosts)
    logger.verbose("DISCOVERY", f"API response: {response.status_code} OK")

    try:
        json_data = response.json()
    except json.JSONDecodeError as err:
        raise NetworkError(
            f"Invalid JSON response from API. Response: {response.text[:200]}"
        ) from err

    logger.debug("DISCOVERY", f"JSON response: {json.dumps(json_data, indent=2)}")

    version_value = _lookup(json_data, version_path, "version_path")
    if not isinstance(version_value, (str, int, float)) or isinstance(
        version_value, bool
    ):
        raise ConfigError(
            f"discovery.version_path {version_path!r} found "
            f"{type(version_value).__name__} in the API response, not a "
            f"version"
        )
    version_str = bounded(str(version_value), "The API's version value")
    logger.verbose("DISCOVERY", f"Extracted version: {version_str}")

    version_pattern = source.get("version_pattern")
    if version_pattern is not None:
        logger.verbose("DISCOVERY", f"Version pattern: {version_pattern}")
        version_str = extract_version(
            version_pattern, version_str, f"the API's version value {version_str!r}"
        )
        logger.verbose("DISCOVERY", f"Version after pattern: {version_str}")

    download_url = _lookup(json_data, download_url_path, "download_url_path")
    if not isinstance(download_url, str) or not download_url:
        raise ConfigError(
            f"discovery.download_url_path {download_url_path!r} found "
            f"{type(download_url).__name__} in the API response, not a URL"
        )
    logger.verbose("DISCOVERY", f"Download URL: {download_url}")

    return RemoteVersion(
        version=version_str,
        download_url=download_url,
        source="api_json",
    )

validate_config

validate_config(app_config: dict[str, Any]) -> list[str]

Validate api_json strategy configuration.

Checks for required fields and correct types without making network calls.

Parameters:

Name Type Description Default
app_config dict[str, Any]

The app configuration from the recipe.

required

Returns:

Type Description
list[str]

List of error messages (empty if valid).

Source code in napt/discovery/api_json.py
def validate_config(self, app_config: dict[str, Any]) -> list[str]:
    """Validate api_json strategy configuration.

    Checks for required fields and correct types without making network calls.

    Args:
        app_config: The app configuration from the recipe.

    Returns:
        List of error messages (empty if valid).

    """
    errors: list[str] = []
    source = app_config.get("discovery", {})

    api_url = require_str(source, "api_url", errors)
    for key in ("version_path", "download_url_path"):
        path = require_str(source, key, errors)
        if path is not None:
            _check_path(path, key, errors)

    headers = source.get("headers")
    if "headers" in source and not isinstance(headers, dict):
        errors.append("discovery.headers: Must be a dictionary")
    elif isinstance(headers, dict):
        for name, value in headers.items():
            field_path = f"discovery.headers.{name}"
            if not isinstance(value, str):
                errors.append(f"{field_path}: Must be a string")
                continue
            errors.extend(
                check_secret_use(app_config, value, api_url or "", field_path)
            )

    version_pattern = optional_str(source, "version_pattern", errors)
    if version_pattern is not None:
        check_regex(version_pattern, "version_pattern", errors)

    return errors