Commit Graph
161 Commits
Author SHA1 Message Date
Dave DeLong a37eca4c8e Expose access token via AuthenticationDelegate (#7536) 2026-08-31 07:47:10 +02:00
Dave DeLong a1781cb28e (Internal) Spend virtual currencies (#7507) 2026-08-27 16:14:19 -06:00
Dave DeLongandÁlvaro Brey 4e98dd2f75 Inject and refresh IAM tokens (#7440)
* ci: announce modifications in the SDK API feed (#7451)

An attribute-only modification is neither an addition nor a break, so it reached the feed as a headline and a link, with the headline claiming new API.

* Implement the IAM network operations

# Conflicts:
#	RevenueCat.xcodeproj/project.pbxproj

# Conflicts:
#	RevenueCat.xcodeproj/project.pbxproj

# Conflicts:
#	Sources/Authentication/Authentication.swift
#	Sources/Identity/IdentityManager.swift
#	Tests/UnitTests/Networking/BackendErrorTests.swift

* target membership

* Inject tokens and attempt to refresh when necessary

* testa and a full comment

* senior engineer, reporting for duty

* custom compilation guard

* retain the authentication instance so errors can be reported

---------

Co-authored-by: Álvaro Brey <alvaro.brey@revenuecat.com>
2026-08-21 14:04:23 -06:00
Dave DeLongandÁlvaro Brey 8349a4afd1 Implement IAM Login Operations (#7439)
* ci: announce modifications in the SDK API feed (#7451)

An attribute-only modification is neither an addition nor a break, so it reached the feed as a headline and a link, with the headline claiming new API.

* Implement the IAM network operations

# Conflicts:
#	RevenueCat.xcodeproj/project.pbxproj

# Conflicts:
#	RevenueCat.xcodeproj/project.pbxproj

* target membership

# Conflicts:
#	RevenueCat.xcodeproj/project.pbxproj

* fix test

* address cursor feedback

* fix imports

* revert fetch policy

* missed one

---------

Co-authored-by: Álvaro Brey <alvaro.brey@revenuecat.com>
2026-08-21 14:04:22 -06:00
Dave DeLongandÁlvaro Brey 3eb01c32bc HTTP Paths can change their absolute path based on IAM enablement (#7422)
* ci: announce modifications in the SDK API feed (#7451)

An attribute-only modification is neither an addition nor a break, so it reached the feed as a headline and a link, with the headline claiming new API.

* HTTP Paths can change their absolute path based on IAM enablement

* missed one

* fix failures

* fix crashing test

* address feedback

* unit tests

* slightly more graceful

* fix signing test

* fix other test

* log on invalid path

* throwAssertion is unavailable on watchOS

* fix backend integration tests

* fix import

---------

Co-authored-by: Álvaro Brey <alvaro.brey@revenuecat.com>
2026-08-21 14:04:21 -06:00
4524b91148 IAM Login part 2 (#7410)
* ci: announce modifications in the SDK API feed (#7451)

An attribute-only modification is neither an addition nor a break, so it reached the feed as a headline and a link, with the headline claiming new API.

* Add the Authentication namespace

* Add TokenManager

* Tests

* add test file to xcodeproj

* Add API tests

* expose authentication property

* swift API test

* more fixes

* lint

* Update baseline swiftinterface files (#7421)

* sigh

* extra parameter

* missing arg

* a couple more

* Fix visibility

* fix backend test compilation

* remove unnecessary delegate parameter

* remove commented-out APIs

* add KeychainAccessGroup api

* -_-

* fix test

* don't include attributes values in the description

* Address feedback

* lint

* address feedback

---------

Co-authored-by: Álvaro Brey <alvaro.brey@revenuecat.com>
Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2026-08-21 14:04:21 -06:00
Dave DeLong 80f6f1a6cb IAM Login, Part 1 (#7398) 2026-08-13 10:57:27 -06:00
e7384b8282 Re-tier HTTP request timeouts around per-host memory (#7179)
* Re-tier HTTP request timeouts around per-source memory

Replaces the single global "recent timeout" slot in `HTTPRequestTimeoutManager`
with a per-host map (`host -> lastTimeoutDate`, 10-minute per-entry expiry,
pruned on access) and re-tiers the request timeouts:

- Main-source, endpoint with no fallback-URL support: 15s base / 5s reduced
- Main-source, endpoint with fallback-URL support: 5s base / 2s reduced
- Fallback-host and proxied requests: flat 30s (never consult the memory)

A main-source request to host H uses the reduced tier iff H has a non-expired
timeout entry. Timeouts are now recorded for any non-fallback request (dropping
the previous fallback-support-only condition), keyed by attempt host; a
successful main-source response clears only that host's entry. Renames the
`timeoutOnMainBackendForFallbackSupportedEndpoint` result to `mainSourceTimedOut`.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Define flat timeout tier as a Timeout constant

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add exhaustive multi-host tests for timeout manager

Co-authored-by: Cursor <cursoragent@cursor.com>

* Honor developer networkTimeout via internal NetworkTimeout enum

Introduce an internal NetworkTimeout enum (.default/.custom) threaded from
Configuration down to HTTPRequestTimeoutManager. When a developer sets
networkTimeout, it replaces the built-in base/flat tiers while the reduced
fail-fast tiers stay fixed.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Add NetworkTimeout.swift to RevenueCat.xcodeproj

The file was only picked up by the SPM/Tuist directory globs, so the
hand-maintained Xcode project build failed to resolve the type.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Gate re-tiered no-fallback timeouts behind usesRemoteConfigAPISources

The aggressive no-fallback fail-fast timeouts and their per-host timeout
recording now apply to main-API requests only when the usesRemoteConfigAPISources
dangerous setting is enabled. With it disabled (the default) the legacy network
timeout is preserved. The gating is a per-call timeout(...) parameter so
blob-source downloads can opt into the re-tiered timeouts independently.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Keep the legacy flat timeout when re-tiered timeouts are off, and share one manager

The fallback-host and proxied tiers returned the new 30s flat timeout regardless of
`usesRemoteConfigAPISources`, halving the legacy 60s (or custom) network timeout for
proxy users and every fallback-host request. They now honor `reTieredTimeoutsEnabled`
like the no-fallback tier does, so only the fallback-supported tiers behave the same
either way.

`Backend` also built one timeout manager per HTTPClient, so the main and remote-config
lanes kept independent per-host memories despite talking to the same hosts. They now
share one, and `HTTPClient` requires both the manager and the network timeout so this
wiring can't be dropped silently.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Clear a host's fail-fast memory as soon as it answers

The memory exists to remember how quickly a host responds, so a non-error
response is evidence the host recovered even when decoding or verifying it
fails afterwards. Deciding off the raw status code instead of the parsed result
keeps those failures from leaving a responsive host stuck on the reduced
timeout tier.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Name the requestTimeoutManager in the fail-fast comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* Tighten comments on the Backend-shared failover and timeout manager

Name the instances the comments describe so it's clear what is shared.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Record API source timeouts before health checks

* Test shared timeout state across backend lanes

* Normalize URL timeout classification across platforms

* Remove unused RemoteConfigAPI test hook

* Skip HTTP stubs lane tests on watchOS

* Treat the remote config fallback path as a fallback host request

`FallbackPath` bakes the fallback host into its `serverHostURL`, but `fallbackUrlIndex` is
nil on those requests, so `isFallbackURLRequest` was false and they were classified as
main-source: with API sources enabled they drew the aggressive 15s/5s no-fallback tiers
instead of the flat fallback timeout, their timeouts armed the per-host fail-fast memory
for the fallback host, and their successes cleared the main source's entry.

Add `isFallbackHostPath` so a path can declare that it targets a fallback host on its own,
and use it alongside the index when picking the tier and updating the memory.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Rick van der Linden <rick.vanderlinden@revenuecat.com>
2026-08-03 14:51:50 +02:00
Antonio PallaresandCursor 30317dc720 feat(remote-config): force the config kill-switch via query param in E2E tests (#7317)
* refactor: model ForceServerErrorStrategy interception as a single Action enum

The two closures (`fakeResponseWithoutPerformingRequest` and
`shouldForceServerError`) encoded an implicit precedence rule that only lived in
a doc comment. A single closure returning `Action` makes each request resolve to
exactly one outcome.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: log the destination URL and faked status code when forcing errors

Both messages previously identified only the request, so a faked 404 and a faked
204 looked identical, and there was no way to tell whether a forced error routed
to the 502 endpoint or to an unreachable host.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(remote-config): force the config kill-switch via force_killswitch query param

The Maestro E2E app faked a local 404 for /v1/config, which never exercised the
backend's real kill-switch response. RevenueCat/khepri#23311 adds an opt-in
`force_killswitch=true` query param that serves the actual 400
CONFIG_ENDPOINT_DISABLED for that request only.

`serverErrorURL` cannot be reused here because it replaces the whole URLRequest,
dropping the method, auth headers and body the endpoint needs.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 16:14:21 +02:00
Antonio PallaresandCursor 96a3102be3 refactor: model ForceServerErrorStrategy interception as a single Action enum (#7315)
* refactor: model ForceServerErrorStrategy interception as a single Action enum

The two closures (`fakeResponseWithoutPerformingRequest` and
`shouldForceServerError`) encoded an implicit precedence rule that only lived in
a doc comment. A single closure returning `Action` makes each request resolve to
exactly one outcome.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: log the destination URL and faked status code when forcing errors

Both messages previously identified only the request, so a faked 404 and a faked
204 looked identical, and there was no way to tell whether a forced error routed
to the 502 endpoint or to an unreachable host.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 11:38:23 +02:00
Rick f620703c93 feat(remote-config): send X-RC-Last-Refresh-Time on config requests (#7308)
* Add config last refresh header

* Refine remote config refresh header

* Address remote config refresh header reviews

* Sign final merged request headers

* Snapshot remote config refresh time

* Improve remote config refresh timestamp tests
2026-07-29 16:39:22 +02:00
Toni RicoandClaude Fable 5 8925524293 feat(remote-config): health-check-gated API source failover in HTTPClient (#7294)
* feat(remote-config): health-check-gated API source failover in HTTPClient

Wires the API source failover into the request pipeline, still behind the
usesRemoteConfigAPISources dangerous setting (internal and defaulting to
false, so released behavior is unchanged):

- Requests resolve their API source once (in start) and carry the handle,
  so a failure can report the exact source unhealthy and ETag/backoff
  retries keep targeting the same host.
- On a failure that points at the host, the source is health-checked
  before failing over: a healthy source surfaces the original error, an
  unhealthy one is reported and the request transparently retries on the
  next source (capped at 5 source attempts per request). The static
  per-endpoint fallback hosts stay the last resort.
- Unlike Android, device-connectivity errors (reusing
  NetworkError.isAllowedToRetryWithFallbackHost) skip the health check
  entirely and surface the original error: switching hosts can't fix a
  device that is offline.
- Both Backend HTTPClients share one APISourceFailover, so they walk one
  source list and share one health-check cache.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(remote-config): end-to-end API source failover integration tests

Port of purchases-android's BackendAPISourceFailoverIntegrationTest: real
Backend.getCustomerInfo through the production wiring (real HTTPClients,
shared APISourceFailover, real SourceHealthChecker probing over the URL
loading system) and a real RemoteConfigSourceProvider fed by an in-memory
sources topic, with OHHTTPStubs standing in for the source hosts and
recording exact per-host request order. Adds the iOS-only
device-connectivity scenario and a dangerous-setting-off wiring check on
top of Android's seven scenarios.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: model the request's API source as a single state enum

Replaces the three loosely coupled Request fields (apiSource,
apiSourceResolved, apiSourceAttemptCount) with one APISourceState enum
(unresolved / noSource / source(_, attemptCount:)), making inconsistent
combinations unrepresentable. No behavior change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: adopt the narrowed APISourceFailover initializer

Passes just the usesRemoteConfigAPISources flag at the two construction
sites, following the signature change in the base branch.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: clarify why static fallback still runs when the source is healthy

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(remote-config): raise the API failover restart interval to 2 hours

The api source list now returns to the primary source 2 hours after it
first failed over instead of 10 minutes. Timer tests derive their time
values from the constant so future changes are single-line.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(remote-config): cover shared failover and probe-in-flight ordering

Addresses review feedback:
- Both HTTPClient lanes share one APISourceFailover: a failover on the
  main lane advances the source list the remote-config lane resolves.
- A request enqueued while a health check is in flight stays queued
  until the probe resolves and runs after the front-queued failover
  retry.
- Bind the source and attempt count in one pattern match at the
  failover guard.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop the APISourceState.attemptCount accessor

Its only caller pattern-matches instead, surfacing the "must already
target a source" assumption at the one place it matters rather than
papering over impossible states with a 0 default.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 17:25:33 +02:00
Rick 5e6d58abf2 Avoid decoding legacy paywall components for workflows (#7264)
* Avoid decoding paywall components with remote config

* Preserve offerings cache when remote config disables

* Prevent stale offerings cache writes after remote config disable

* Clarify offerings decoding mode naming

* Separate offerings fetch data from cached contents

* Address offerings cache review feedback

* Require explicit cache decoders

* Test offerings cache version compatibility
2026-07-27 10:21:57 +02:00
c4d824d68c feat(remote-config): source API base host from remote-config sources (#7123)
* feat(remote-config): wire manager behind feature flag

* fix(remote-config): only mark refresh fresh after cache write

* feat(remote-config): source API base host from remote-config sources

Resolve the API base host from the shared RemoteConfigSourceProvider (with
the embedded defaults as a floor) instead of the hardcoded apiBaseURL, so
requests can fail over across API hosts. proxyURL and an overridden
apiBaseURL still pin the host and bypass API sources, and per-endpoint
fallback URLs are unchanged.

The provider is created once in the composition root (gated on
remoteConfigEnabled) and injected explicitly into Backend/HTTPClient; nil
preserves the existing SystemInfo.apiBaseURL behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): derive nullable API source provider and manager from remoteConfigEnabled

Create the RemoteConfigSourceProvider (and its shared on-disk cache) up front,
gated on remoteConfigEnabled, and build the RemoteConfigManager from the
provider's nullability after Backend exists so it can reuse backend.remoteConfigAPI.
Keeps a single shared source provider + disk cache across the networking layer
and the manager, and avoids touching the disk cache directory when remote config
is disabled.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): drop redundant remote-config wiring comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): drop redundant remote-config manager comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): simplify APISourceProviding doc comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): always wire API source provider, gate only disk cache

Create the RemoteConfigSourceProvider unconditionally and inject it into
Backend/HTTPClient so main-API host resolution runs even when remote config
is disabled (embedded default sources as the floor). Only the on-disk cache
and the real RemoteConfigManager stay gated on remoteConfigEnabled; the
provider's topic store is now optional (nil means defaults-only).

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): rename APISourceProviding to APISourceProviderType

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(remote-config): resolve web billing host from API sources

The web billing paths are hosted on the same api.revenuecat.com host as the
main API, so they should resolve their base host from the API source provider
too (with failover) instead of the static serverHostURL.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): drop redundant web billing API-sources comments

The comments restated what the code and surrounding context already convey.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(remote-config): assert ETag retry stays on the API source host

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(remote-config): drop APISourceProviderType, use RemoteConfigSourceProviderType directly

The networking layer depended on the narrow APISourceProviderType protocol, an extra
abstraction over RemoteConfigSourceProviderType that added little. Fold currentAPISource()
into RemoteConfigSourceProviderType and have HTTPClient/Backend depend on it directly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(remote-config): wire apiSourceProvider into dedicated remote-config lane

The main-into-branch merge left `HTTPClient.dedicatedRemoteConfig` (and its
call site) without the new `apiSourceProvider` argument, breaking compilation.
Thread the provider through so the dedicated `/config` lane also resolves its
base host from remote-config API sources, matching the main lane.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: gate remote-config API sources behind usesRemoteConfigAPISources

Resolve main-API request hosts from the remote-config API sources only when
the `usesRemoteConfigAPISources` dangerous setting is enabled. When disabled
(the default), requests keep targeting the static `SystemInfo.apiBaseURL`.

Enable the setting in the API-source `HTTPClient` tests and add a test
asserting an injected provider is ignored while the setting is off.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(test): pass apiSourceProvider in BackendRemoteConfigLaneTests HTTPClient init

The lane test constructed HTTPClient without the now-required apiSourceProvider
argument, breaking compilation of the unit test target after merging main.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Rick van der Linden <rick.vanderlinden@revenuecat.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-17 08:56:01 +02:00
Rick b82223e5a1 feat(remote-config): add static fallback config endpoint (#7182)
* feat(remote-config): add static fallback config endpoint

* refactor(remote-config): clarify static fallback path name

* test(remote-config): cover static fallback signature failures

* fix(remote-config): use static fallback only without cache

* test(remote-config): cover static fallback external blobs

* refactor(remote-config): align static fallback naming

* refactor(remote-config): scope static fallback path

* fix(remote-config): mark fallback no content fresh

* fix(remote-config): align fallback accept headers

* refactor(remote-config): rename fallback endpoint types

* fix(remote-config): enable etags for fallback config

* fix(remote-config): skip fallback when proxy is configured

* fix(remote-config): rely on etag cache for fallback

* refactor(remote-config): reuse fallback retry eligibility

* fix(remote-config): disable after fallback client errors
2026-07-10 14:17:31 +02:00
Antonio PallaresandCursor cbdc1ae216 Don't switch hosts on device-connectivity errors (#7176)
* other(networking): don't switch hosts on device-connectivity errors

Add `NetworkError.isDeviceConnectivityError` (true only for device-side
URLError codes) and narrow the fallback-host retry gate to
`isTransient && !isDeviceConnectivityError`, so a device that is offline
no longer triggers pointless host switching. Host-side and ambiguous
failures stay switch-eligible.

Co-authored-by: Cursor <cursoragent@cursor.com>

* other(networking): make isDeviceConnectivityError doc less usage-specific

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-10 12:06:50 +02:00
Facundo Menzella de6bccae28 other(networking): remove unused workflows OperationQueue and HTTP path cases (#7145)
Follow-up to the dead-endpoint-subsystem deletion: the dedicated
workflows OperationQueue (allocated on every Backend init, capped at
4 concurrent operations) was only ever consumed by the now-deleted
WorkflowsAPI, and HTTPRequestPath's .getWorkflow/.getWorkflows cases
had no remaining production caller. Confirmed via grep before removal.
2026-07-08 13:08:08 +02:00
RickandRevenueCat Git Bot f4c06c1f4a feat(remote-config): add rc container compression support (#7107)
* feat(remote-config): add rc container compression support

* fix(remote-config): use rc element encoding header

* test(remote-config): align rc container warning logs

* Update baseline swiftinterface files (#7108)

* fix(remote-config): remove unused accept encoding header case

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2026-07-01 11:58:03 +02:00
Rick 00251c6e02 feat(remote-config): switch config request to v1 and send app user id (#7080)
* fix(remote-config): use v1 config endpoint

* feat(remote-config): include app user id in request

* feat(remote-config): move domain into config path

* fix(remote-config): always encode prefetched blobs

* chore(remote-config): remove redundant coding key comment

* fix(remote-config): update nonce path test
2026-06-29 13:25:55 +02:00
Rick 48e61c41e9 refactor(remote-config): make rc container validation domain-specific (#7074)
* feat(remote-config): make rc container validation domain-specific

* refactor(remote-config): share config element validation

* refactor(remote-config): decode remote config container in http client

* fix(remote-config): align rebased container tests

* fix(remote-config): fix remote config signature verification

* docs(remote-config): clarify rc container validation comments
2026-06-29 12:19:58 +02:00
Rick cf77437cc0 feat(remote-config): verify RC container signatures (#7046)
* feat(remote-config): use opaque manifest token models

* fix(remote-config): simplify manifest token model

* feat(remote-config): verify RC container signatures

* refactor(remote-config): isolate signature payload context

* refactor(remote-config): clarify fetch and signing context

* fix(remote-config): log signature payload failures

* fix(remote-config): correct checksum mismatch verification tests

* fix(remote-config): clarify checksum mismatch test behavior

* fix(remote-config): expect enforced checksum verification failure

* fix(remote-config): address signing review feedback

* fix(remote-config): verify no-content response context

* fix(remote-config): expect no-content verification failure code

* refactor(remote-config): group signature verified paths
2026-06-25 17:03:58 +02:00
Rick 6330937692 feat(remote-config): support RC Container format in network stack and use for remote-config request (#7037)
* feat(remote-config): request RC Container format

* fix(remote-config): handle no content responses

* chore(remote-config): allow snapshot todo

* fix(remote-config): disable response verification

* chore(remote-config): document disabled signing

* refactor(remote-config): parse RC containers in HTTP stack
2026-06-19 14:38:38 +02:00
d4f0fb2686 refactor(ads): reuse SDK retry classification for poll errors (#7009)
* refactor(ads): move rewardverification to coresdk

* refactor(ads): move rewardverification to coresdk

* refactor(ads): move rewardverification to coresdk

* refactor(ads): remove unnecessary comment

* fix(ads): linter and behavior fixes

* fix(ads): gate reward-verification VC cache invalidation out of CustomEntitlementComputation

* refactor(ads): rename reward-verification transactionId → clientTransactionID

* fix(ads): remove duplicated SSV payload logic from AdMob adapter

* chore(ads): cover install via injectable

* chore(ads): fix linter

* refactor(ads): introduce RewardVerificationToken

* refactor(ads): add reward_verification_completed log

* Update AdapterSDKs/RevenueCatAdMob/Tests/RevenueCatAdMobTests/PresentRewardVerificationTests.swift

Co-authored-by: Antonio Pallares <ajpallares@users.noreply.github.com>

* fix(ads): linter

* fix(ads): key reward verification poll retries on HTTP status

Retry network/offline transport errors and any HTTP 5xx during reward
verification polling, keying on the HTTP status code rather than the
mapped ErrorCode. Empty/unparseable 5xx responses are now retried, and
4xx client errors fail fast as .backendError instead of being retried to
a misleading .timeout.

* refactor(ads): drop redundant comments on poll retry classifier

* refactor(ads): read poll HTTP status via typed NSError accessor

* refactor(ads): reuse SDK retry classification for poll errors

Classify reward-verification poll retries from the structured BackendError
instead of re-deriving the HTTP status from a flattened public NSError.

Adds a reusable NetworkError.isTransient (5xx and connection-level failures
are transient, 4xx are terminal) and forwards it from BackendError; the
HTTPClient fallback-host retry check now delegates to it. The poll path keeps
the structured BackendError via an internal fetchRewardVerificationStatus,
letting the poller reuse BackendError.isTransient and dropping the bespoke
NSError.httpStatusCode accessor.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(ads): switch from experimental to internal

* docs(ads): reference BackendError in Poller doc comment

---------

Co-authored-by: Peter Porfy <peter.porfy@revenuecat.com>
Co-authored-by: Pol Miro <polmiro@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 03:45:52 -06:00
Rosie Watson 50a1b541cb WFL-303 | Add fallback URL for workflows (#7008)
* chore: add fallback url for workflows

* test: add test

* chore: address comments about type param
2026-06-16 08:06:51 +01:00
f98f57f8e9 fix(workflows): Don't serve stale workflows when the backend rejects the request (#6946)
* fix(workflows): don't restore stale workflows from disk on a 4xx

The getWorkflowsList failure branch restored the cached list + details
on any error. That's right for transient errors (5xx / offline) but
wrong for a 4xx, where the backend is authoritatively rejecting the
request (workflows disabled, unauthorized), so we shouldn't serve stale
prefetched data.

Generalize the existing offerings classification into
BackendError/NetworkError.shouldFallBackToCache (the offerings property
now delegates to it, no behavior change) and gate the workflows disk
restore on it. 4xx skips the restore; 5xx and connection failures still
restore.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(workflows): fill gaps found in code review of 4xx stale-restore fix (#6948)

- testGetWorkflowsListCallsOnCompleteOnClientError: verifies onComplete()
  fires on 4xx even though disk restore is skipped (callers must not block)
- testGetWorkflowsListRestoresDetailsFromDiskOnServerError: verifies that
  on 5xx both list mapping AND workflow details are restored from disk, not
  just the list mapping

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: drop redundant shouldFallBackToCachedOfferings alias

Per review: shouldFallBackToCachedOfferings was only a thin delegate to
shouldFallBackToCache after the prior refactor. Remove it on NetworkError
and BackendError and point callers (OfferingsManager, tests) at
shouldFallBackToCache directly. Behavior-preserving.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Cesar de la Vega <664544+vegaro@users.noreply.github.com>
2026-06-08 19:41:52 +00:00
Rick 7ee15c73a2 feat(remote-config): add network scaffolding for GET /v2/config endpoint (#6854)
* feat(remote-config): add network scaffolding for GET /v2/config endpoint

Adds RemoteConfigResponse model, GetRemoteConfigOperation, RemoteConfigAPI,
and wires everything into Backend. Unknown topic keys in the manifest are
silently dropped for forward compatibility. Mirrors Android PR #3435.

* fix(remote-config): use lowercase "default" variant key in test fixtures

Aligns with Android convention (DEFAULT_ENTRY_ID = "default") established
in purchases-android PR #3437.

* test(remote-config): add snapshot files for all CI OS versions

BackendGetRemoteConfigTests was only recording snapshots for iOS 26.
CI also runs tests on iOS 14/15/16/17/18, tvOS 18, macOS, and watchOS,
each of which requires its own snapshot file.

Derived from existing snapshot patterns in BackendGetRewardVerificationStatusTests.

* fix(remote-config): log warning when unknown topic key is received

Follows the codebase convention of logging unknown backend values
(e.g. WorkflowsResponse unknown_workflow_trigger_type) rather than
silently dropping them.

* refactor(remote-config): rename wireKey to rawValue, add WIP comment for signature verification

Aligns Topic with Swift's RawRepresentable convention and matches the
Android SDK's comment indicating signature verification will be enabled
once the remote config endpoint is finalized.

* refactor(remote-config): enable etag and simplify HTTPRequestPath cases
2026-06-02 17:19:05 +02:00
Facundo MenzellaandClaude Sonnet 4.6 a3ea621584 feat(networking): add getWorkflows list endpoint (#6853)
* feat(networking): add getWorkflows list endpoint

Port of https://github.com/RevenueCat/purchases-android/pull/3509

Adds WorkflowSummary and WorkflowsListResponse models, GetWorkflowsListOperation,
and WorkflowsAPI.getWorkflows() to support listing a subscriber's workflows via
GET /v1/subscribers/{userId}/workflows. Includes request deduplication and
background-aware delay, matching the existing getWorkflow(by id) pattern.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add WorkflowsListCallback and GetWorkflowsListOperation to Xcode project

Register the two new source files in the root RevenueCat.xcodeproj so
xcodebuild (used by CI) can find them. SPM discovers them automatically
but the tracked root project needs explicit file references and build
file entries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix snapshots: remove ?type=paywall query param from getWorkflows endpoint

The getWorkflows endpoint does not send a type filter query parameter.
The snapshots were created from an earlier design and needed to be
updated to match the actual request URL.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix WorkflowSummary decoding with JSONDecoder.default convertFromSnakeCase

JSONDecoder.default uses .convertFromSnakeCase, which converts JSON keys to
camelCase before matching against CodingKey raw values. The explicit CodingKeys
had snake_case raw values (e.g. "display_name"), causing a mismatch since the
decoder would convert display_name to displayName before the lookup.

Removing the explicit CodingKeys lets Swift synthesize them with camelCase raw
values, which correctly match the converted keys.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(networking): add type filter parameter and deserialization robustness tests

- Add optional `type: String?` parameter to `getWorkflows` path, operation,
  API method, and mock, matching Android PR #3509 which supports
  `?type=<value>` query filtering on the list endpoint
- Include `type` in the operation deduplication cache key so calls with
  different types are not coalesced
- Add `testGetWorkflowsWithTypePassesQueryParameter` with snapshots for all
  OS variants
- Add `WorkflowSummaryDecodingTests` covering explicit-null `offering_id`,
  absent `prefetch` default, and unknown-field tolerance for both
  `WorkflowSummary` and `WorkflowsListResponse`
- Remove unnecessary `import Foundation` from `WorkflowsListCallback.swift`

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Address review: enable signature verification for getWorkflows, fix cache key separator and indentation

- Move .getWorkflows to supportsSignatureVerification=true, matching .getWorkflow and Android PR (#3509)
- Add "\n" separator between appUserID and type in individualizedCacheKeyPart to prevent collision
- Fix indentation of factory closure closing brace and label to match GetWorkflowOperation pattern

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 07:31:12 +02:00
Pol MiroandAntonio Pallares 7d7d584634 Rename internal SSV symbols, URL and metric to RewardVerification (#6667)
* Rename internal AdMobSSV symbols, URL and metric to RewardVerification

Renames the internal AdMobSSV* types and SPI introduced in #6641 to
RewardVerification* so the wording stays adapter-agnostic. Also renames
the backend URL path and the client-side metric to match, so the SPI is
provider-agnostic end to end.

Renames:
- Sources/Ads/AdMobSSV/ -> Sources/Ads/RewardVerification/
- AdMobSSVPollStatus -> RewardVerificationPollStatus
- RewardVerificationPollStatus.validated -> .verified
- AdMobSSVStatusResponse -> RewardVerificationStatusResponse
- RewardVerificationStatusResponse.Status.validated -> .verified
  (the decoder still accepts the legacy "validated" wire value during
  the rollout window; covered by a new decoder unit test)
- AdMobSSVStatusCallback -> RewardVerificationStatusCallback
- GetAdMobSSVStatusOperation -> GetRewardVerificationStatusOperation
- AdsAPI.getAdMobSSVStatus -> getRewardVerificationStatus
- Purchases.pollAdMobSSVStatus -> pollRewardVerificationStatus
- HTTPRequest.Path.adMobSSVStatus -> .rewardVerificationStatus
- URL path: /ads/admob/ssv/{tx} -> /ads/reward_verifications/{tx}
- Metric name: get_admob_ssv_status -> get_reward_verification_status
- BackendErrorStrings.unknown_admob_ssv_status -> .unknown_reward_verification_status
- Test files, test methods and snapshot artifacts renamed to match.
- Xcode project file references updated in lockstep.

* Drop legacy `validated` wire-value compat in RewardVerification decoder

The `RewardVerificationStatusResponse` decoder was accepting both `"verified"`
and the legacy `"validated"` status from the backend as a backwards-compat
hedge during rollout. The endpoint has not been shipped and the SDK has no
public entry point that polls it yet, so there is no compatibility window to
preserve — the decoder can require `"verified"` outright.

While here, simplify the decoder to look up known cases via
`Status(rawValue:)` instead of a string-literal switch, so adding a future
case can't silently drift from the enum.

Removes the corresponding `testDecodesLegacyValidatedWireValueAsVerified`
test. Existing coverage for `verified`, `pending`, `failed`, and the
`unknown` fallback (with the `Logger.warn` assertion) is unchanged.

* Update Sources/Purchasing/Purchases/Purchases.swift

Co-authored-by: Antonio Pallares <ajpallares@users.noreply.github.com>

* test: assert warning is logged when decoding literal "unknown" status

Address review feedback: cover the case where the backend sends the
literal "unknown" wire value, which still falls through the
unmapped-status branch and should emit a warning.

---------

Co-authored-by: Antonio Pallares <ajpallares@users.noreply.github.com>
2026-04-23 13:57:32 +02:00
23d012abe2 Add workflow-based paywall resolution (#6675)
* Add workflows network layer for multipage paywalls

- Add `getWorkflows` and `getWorkflow` endpoint paths
- Add `WorkflowsListResponse` and `PublishedWorkflow` response models
- Add `WorkflowDetailProcessor` to handle `inline`/`use_cdn` response actions
- Add `WorkflowCdnFetcher` protocol and `DirectWorkflowCdnFetcher` implementation
- Add `GetWorkflowsOperation` and `GetWorkflowOperation` cacheable network operations
- Add `WorkflowsAPI` facade and wire into `Backend`
- Add unit tests for all new components

iOS equivalent of https://github.com/RevenueCat/purchases-android/pull/3300

Made-with: Cursor

* fix xcodeproj

* reset Package.resolved

* Update WorkflowStep models to match actual backend response

- Add WorkflowTrigger struct (name, type, action_id, component_id)
- Add triggers, outputs, and metadata fields to WorkflowStep
- Add metadata field to PublishedWorkflow
- Remove value field from WorkflowTriggerAction (backend uses step_id only)

Made-with: Cursor

* Update WorkflowResponseTests to match updated models

- Replace value/resolvedTargetStepId assertions with stepId
- Remove testDecodeWorkflowTriggerActionValueTakesPrecedence (value field removed)
- Add testDecodeWorkflowTrigger for new WorkflowTrigger struct
- Add testDecodePublishedWorkflowWithMetadata
- Update testDecodeWorkflowStepDefaults to cover triggers, outputs, metadata
- Add testDecodeWorkflowStepMatchingActualBackendResponse with real backend payload

Made-with: Cursor

* Disable file_length lint rule in HTTPRequestPath.swift

Made-with: Cursor

* Fix GetWorkflowOperation to compute result once before distributing to callbacks

CDN fetch and JSON decoding were running once per deduplicated callback.
Compute the Result<WorkflowFetchResult, BackendError> once outside the
performOnAllItemsAndRemoveFromCache loop, matching the pattern used by
GetOfferingsOperation and other operations in the codebase.

Made-with: Cursor

* Fix CDN fetcher: use URLSession instead of Data(contentsOf:), classify errors correctly

- Replace Data(contentsOf:) with URLSession.shared.dataTask + DispatchSemaphore
  in DirectWorkflowCdnFetcher; gets URLSession timeout, HTTP status validation,
  and proper network stack semantics
- Add WorkflowDetailProcessingError.cdnFetchFailed typed error so CDN I/O
  failures are distinguishable from envelope parsing failures
- Catch cdnFetchFailed in GetWorkflowOperation and map to NetworkError.networkError
  instead of NetworkError.decoding, fixing misleading error classification
- Update WorkflowDetailProcessorTests to assert the typed error is thrown

Made-with: Cursor

* Replace semaphore CDN fetch with async/await using withCheckedThrowingContinuation

- Make WorkflowCdnFetcher.fetchCompiledWorkflowData async throws; use
  withCheckedThrowingContinuation to bridge URLSession.dataTask into async,
  avoiding any thread-blocking
- Make WorkflowDetailProcessor.process async throws to propagate async
- Bridge into async in GetWorkflowOperation via Task {}; completion() is
  called inside the Task after CDN fetch and decoding complete
- Update WorkflowDetailProcessorTests to async throws with await

Made-with: Cursor

* Make CDN fetcher and processor completion-handler based for consistency

Avoids Task{} in GetWorkflowOperation and keeps all operations calling
completion() synchronously from within the HTTP callback, matching every
other operation in the codebase.

- WorkflowCdnFetcher.fetchCompiledWorkflowData now takes a completion handler;
  DirectWorkflowCdnFetcher uses URLSession.dataTask (non-blocking, no semaphore)
- WorkflowDetailProcessor.process now takes a completion handler; inline action
  completes synchronously, use_cdn fans out to the fetcher callback
- GetWorkflowOperation splits into getWorkflow/handleResponse/backendResult/
  distribute helpers to stay within line-length limits
- WorkflowDetailProcessorTests updated to use waitUntilValue pattern

Made-with: Cursor

* Fix ambiguous cache key delimiter in GetWorkflowOperation

Space-separated appUserID+workflowId could collide (e.g. user 'a b' + workflow 'c'
== user 'a' + workflow 'b c'). Use newline as delimiter, matching the precedent
set by GetWebBillingProductsOperation.

Made-with: Cursor

* PR comments

* remove cdn fetcher

* fix response in BackendGetWorkflowsTests.swift

* fix WorkflowResponseTests

* fix error

* [skip ci] Generating new test snapshots (#6584)

* [skip ci] Generating new test snapshots (#6585)

* [skip ci] Generating new test snapshots (#6586)

* [skip ci] Generating new test snapshots (#6587)

* [skip ci] Generating new test snapshots (#6588)

* [skip ci] Generating new test snapshots (#6589)

* [skip ci] Generating new test snapshots (#6590)

* Test CDN mock is not re-assignable per test

* [skip ci] Generating new test snapshots (#6597)

* [skip ci] Generating new test snapshots (#6598)

* [skip ci] Generating new test snapshots (#6599)

* [skip ci] Generating new test snapshots (#6600)

* [skip ci] Generating new test snapshots (#6601)

* [skip ci] Generating new test snapshots (#6602)

* [skip ci] Generating new test snapshots (#6603)

* getWorkflow is signed

* add type parameter

* add response verification for CDN response

* remove workflows list

* add value to WorkflowTriggerAction

* step id

* hash and filerepo

* missingCdnHash

* linter and project

* fix project

* revert Package.resolved

* @unchecked Sendable

* use hash in generateOrGetCachedFileURL

* fix compilation

* skip responseVerificationMode in cdn

* change basePath of caches

* Add workflow-based paywall resolution (iOS parity with Android #3350)

Implements the workflows endpoint so paywalls can be resolved from a
workflow document rather than the offerings cache, gated behind the
ENABLE_WORKFLOWS_ENDPOINT compile flag. Validates the step→screen→
offeringId chain and maps the workflow screen into Offering.PaywallComponents
using the existing V2 rendering path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add tests for workflow networking layer and WorkflowScreenMapper

BackendGetWorkflowTests covers HTTP call, request caching, per-user and
per-workflow-ID deduplication, error propagation, empty appUserID, and
full response decoding. WorkflowScreenMapperTests verifies all
PaywallComponentsData fields and the UIConfig are mapped correctly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* remove reserialization

* Use explicit type in GetWorkflowOperation.createFactory for greppability

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Use explicit type in GetWorkflowOperation.createFactory for greppability

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix lint errors and refactor workflow offering resolution into PaywallViewConfiguration

- Add swiftlint:disable comments for _revision identifier name in WorkflowsResponse.swift
- Add missing_docs disable in WorkflowsResponse.swift (all @_spi(Internal) types)
- Add file_length disable in Offering.swift
- Fix identifier name 'd' → 'doubleValue' in WorkflowDetailProcessorTests.swift
- Move workflow offering resolution from PaywallView into PaywallViewConfiguration.resolveOfferingOrThrow()
- Add cachedInitialOffering() to PaywallViewConfiguration.Content
- Add PaywallViewConfigurationTests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix swiftlint identifier_name violation in WorkflowDetailProcessorTests

Rename short variable `d` to `doubleValue` in two `if case .double(let d)`
patterns to satisfy the identifier_name rule requiring names >= 3 characters.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Inject PaywallPurchasesType into offering resolution; remove dead code

- Add offerings(), cachedOfferings, and workflow() to PaywallPurchasesType
  so PaywallViewConfiguration.Content no longer calls Purchases.shared directly
- Thread purchases through cachedInitialOffering/resolveOffering/resolveOfferingOrThrow
  and all private helpers; callers pass purchaseHandler.purchasesInstance
- Expose purchasesInstance on PurchaseHandler for call sites
- Add stubs to NotConfiguredPurchases, LoadingPaywallPurchases, and MockPurchases
  (MockPurchases gets offeringsBlock/workflowBlock for test injection)
- Remove dead WorkflowDetailProcessingError.missingInlineData case
- Replace manual JSONSerialization parseEnvelope with Data.asJSONDictionary()
- Collapse double #if nesting into single compound condition
- Remove WHAT doc comment from WorkflowDetailProcessor
- Refactor resolveOffering() to delegate to resolveOfferingOrThrow()
- Parallelize workflow + offerings fetches with async let

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Move offering resolution from Content to PurchaseHandler

Resolving an offering requires a purchases instance, so it belongs on
PurchaseHandler rather than as a method on the Content enum that takes
purchases as a parameter. purchasesInstance accessor removed.

Also fix MockPurchases.map() to forward offeringsBlock, workflowBlock,
and cachedOfferings to the mapped instance, and simplify
PaywallViewConfigurationTests to use MockPurchases directly instead of
configuring a real Purchases singleton.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add clarifying comment to workflow(forOfferingIdentifier:) explaining parameter naming

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix CI failures: remove duplicate switch cases and add @_spi(Internal) to test imports

- Remove duplicate .getWorkflow cases in HTTPRequestPath.swift switches
  (auto-merge artifact that caused duplicate_conditions lint violations)
- Add @_spi(Internal) to @testable imports in three unit test files so they
  can access WorkflowFetchResult, PublishedWorkflow, and WorkflowStep which
  are now @_spi(Internal) public

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix @_spi access in WorkflowDetailProcessorTests

WorkflowResponseTests already had @_spi(Internal) @testable import RevenueCat;
WorkflowDetailProcessorTests was missing the @_spi annotation, causing
'id', 'steps', and 'initialStepId' to be inaccessible on PublishedWorkflow.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix MockWorkflowsAPI.swift missing from StoreKitUnitTests and UnitTests targets

The PBXBuildFile entries for DB7EA77F2F9764F700BCC082 and DB7EA7802F9764F700BCC082
were referenced in the StoreKitUnitTests and UnitTests source phases but never
defined, causing MockWorkflowsAPI to be missing at compile time and
MockBackend.swift to fail with 'cannot find MockWorkflowsAPI in scope'.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add offering_identifier field to WorkflowScreen for parity with Android

Android PR #3350 split offering_id (internal ID) from offering_identifier
(human-readable identifier used for lookup). iOS was only decoding
offering_id and using it for the offering lookup, which would fail if the
workflow response sends the public identifier in offering_identifier.

- Add offeringIdentifier (from offering_identifier) to WorkflowScreen
- Update PurchaseHandler to prefer offeringIdentifier, falling back to offeringId
- Fix typo: workflow.screelns -> workflow.screens
- Add decode tests for both offering fields

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix WorkflowResponseTests: add missing padding field to stack component fixtures

Stack component decoding requires a padding field; test JSON fixtures were
missing it causing keyNotFound decode errors.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix WorkflowResponseTests: add missing margin field to stack component fixtures

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Replace ENABLE_WORKFLOWS_ENDPOINT compile flag with runtime argument check

The -EnableWorkflowsEndpoint launch argument replaces the compile-time flag,
allowing workflow resolution to be toggled without rebuilding.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add Workflow presentation mode to PaywallsTester

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Remove offeringId shim, allow no-paywall offerings to open as workflows

- Drop WorkflowScreen.offeringId / offering_id CodingKey (Android already
  uses offering_identifier exclusively — aligns both platforms)
- Simplify PurchaseHandler to use screen.offeringIdentifier directly
- No-paywall offerings in PaywallsTester now render as tappable rows
  (workflow mode) instead of plain read-only text, with a context menu
  restricted to the Workflow option

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Rename WorkflowFetchResult to WorkflowDataResult, extract ProcessInfo extension

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix project

---------

Co-authored-by: Cesar de la Vega <664544+vegaro@users.noreply.github.com>
Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 10:01:14 +00:00
Pol MiroandRevenueCat Git Bot abad547968 AdMob SSV: add @_spi(Internal) poll endpoint on Purchases (#6641)
* Add AdMob SSV poll endpoint and `pollAdMobSSVStatus` SPI

* Trim verbose AdMob SSV transport comments.

Align AdsAPI and cache-key inline documentation with existing repository comment density while preserving behavior.

* Trim pollAdMobSSVStatus SPI documentation.

Reduce prescriptive guidance in the internal API comment while keeping the key cancellation behavior note.

* [skip ci] Generating new test snapshots (#6648)

* [skip ci] Generating new test snapshots (#6647)

* [skip ci] Generating new test snapshots (#6646)

* [skip ci] Generating new test snapshots (#6645)

* [skip ci] Generating new test snapshots (#6644)

* [skip ci] Generating new test snapshots (#6642)

* [skip ci] Generating new test snapshots (#6643)

* Trigger CI for PR 6641 checks.

Add a non-skip commit so required CircleCI statuses are reported on the current head.

* Validate non-empty client transaction ID for AdMob SSV polling.

Guard against empty client transaction IDs in the SPI and backend operation and add focused backend tests for the new error path.

* [skip ci] Generating new test snapshots (#6652)

* [skip ci] Generating new test snapshots (#6653)

* Trigger CI for PR 6641 checks.

Add a non-skip commit so required CircleCI statuses are reported on the current head.

* Enable signature verification for AdMob SSV status path.

Update HTTP request path tests to cover AdMob SSV signature and nonce behavior.

* fix: address review — move AdMob SPI extension to dedicated file

* fix: address review — fail fast when AdMob status mock is unstubbed

* fix: address review — dedupe client transaction validation in backend operation

* fix: address review — use enum for AdMob SSV poll status

* fix: address review — allow extracted Purchases extensions to access backend

* fix: address review — log unknown AdMob SSV statuses

* fix: address review — add Purchases AdMob SSV mapping tests

* fix: address review — map missing client transaction ID to configuration error

* fix: address review — keep backend private by co-locating AdMob extension

* fix: address review — remove unused raw-value conformance

* fix: address review — assert warning log for unknown AdMob status

* fix: address review — surface unknown AdMob SSV status to adapters

* fix: address review — enable eTag support for AdMob SSV status path

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2026-04-22 15:55:13 +02:00
0b65086ec2 Add workflows network layer for multipage paywalls (#6557)
* Add workflows network layer for multipage paywalls

- Add `getWorkflows` and `getWorkflow` endpoint paths
- Add `WorkflowsListResponse` and `PublishedWorkflow` response models
- Add `WorkflowDetailProcessor` to handle `inline`/`use_cdn` response actions
- Add `WorkflowCdnFetcher` protocol and `DirectWorkflowCdnFetcher` implementation
- Add `GetWorkflowsOperation` and `GetWorkflowOperation` cacheable network operations
- Add `WorkflowsAPI` facade and wire into `Backend`
- Add unit tests for all new components

iOS equivalent of https://github.com/RevenueCat/purchases-android/pull/3300

Made-with: Cursor

* fix xcodeproj

* reset Package.resolved

* Update WorkflowStep models to match actual backend response

- Add WorkflowTrigger struct (name, type, action_id, component_id)
- Add triggers, outputs, and metadata fields to WorkflowStep
- Add metadata field to PublishedWorkflow
- Remove value field from WorkflowTriggerAction (backend uses step_id only)

Made-with: Cursor

* Update WorkflowResponseTests to match updated models

- Replace value/resolvedTargetStepId assertions with stepId
- Remove testDecodeWorkflowTriggerActionValueTakesPrecedence (value field removed)
- Add testDecodeWorkflowTrigger for new WorkflowTrigger struct
- Add testDecodePublishedWorkflowWithMetadata
- Update testDecodeWorkflowStepDefaults to cover triggers, outputs, metadata
- Add testDecodeWorkflowStepMatchingActualBackendResponse with real backend payload

Made-with: Cursor

* Disable file_length lint rule in HTTPRequestPath.swift

Made-with: Cursor

* Fix GetWorkflowOperation to compute result once before distributing to callbacks

CDN fetch and JSON decoding were running once per deduplicated callback.
Compute the Result<WorkflowFetchResult, BackendError> once outside the
performOnAllItemsAndRemoveFromCache loop, matching the pattern used by
GetOfferingsOperation and other operations in the codebase.

Made-with: Cursor

* Fix CDN fetcher: use URLSession instead of Data(contentsOf:), classify errors correctly

- Replace Data(contentsOf:) with URLSession.shared.dataTask + DispatchSemaphore
  in DirectWorkflowCdnFetcher; gets URLSession timeout, HTTP status validation,
  and proper network stack semantics
- Add WorkflowDetailProcessingError.cdnFetchFailed typed error so CDN I/O
  failures are distinguishable from envelope parsing failures
- Catch cdnFetchFailed in GetWorkflowOperation and map to NetworkError.networkError
  instead of NetworkError.decoding, fixing misleading error classification
- Update WorkflowDetailProcessorTests to assert the typed error is thrown

Made-with: Cursor

* Replace semaphore CDN fetch with async/await using withCheckedThrowingContinuation

- Make WorkflowCdnFetcher.fetchCompiledWorkflowData async throws; use
  withCheckedThrowingContinuation to bridge URLSession.dataTask into async,
  avoiding any thread-blocking
- Make WorkflowDetailProcessor.process async throws to propagate async
- Bridge into async in GetWorkflowOperation via Task {}; completion() is
  called inside the Task after CDN fetch and decoding complete
- Update WorkflowDetailProcessorTests to async throws with await

Made-with: Cursor

* Make CDN fetcher and processor completion-handler based for consistency

Avoids Task{} in GetWorkflowOperation and keeps all operations calling
completion() synchronously from within the HTTP callback, matching every
other operation in the codebase.

- WorkflowCdnFetcher.fetchCompiledWorkflowData now takes a completion handler;
  DirectWorkflowCdnFetcher uses URLSession.dataTask (non-blocking, no semaphore)
- WorkflowDetailProcessor.process now takes a completion handler; inline action
  completes synchronously, use_cdn fans out to the fetcher callback
- GetWorkflowOperation splits into getWorkflow/handleResponse/backendResult/
  distribute helpers to stay within line-length limits
- WorkflowDetailProcessorTests updated to use waitUntilValue pattern

Made-with: Cursor

* Fix ambiguous cache key delimiter in GetWorkflowOperation

Space-separated appUserID+workflowId could collide (e.g. user 'a b' + workflow 'c'
== user 'a' + workflow 'b c'). Use newline as delimiter, matching the precedent
set by GetWebBillingProductsOperation.

Made-with: Cursor

* PR comments

* remove cdn fetcher

* fix response in BackendGetWorkflowsTests.swift

* fix WorkflowResponseTests

* fix error

* [skip ci] Generating new test snapshots (#6584)

* [skip ci] Generating new test snapshots (#6585)

* [skip ci] Generating new test snapshots (#6586)

* [skip ci] Generating new test snapshots (#6587)

* [skip ci] Generating new test snapshots (#6588)

* [skip ci] Generating new test snapshots (#6589)

* [skip ci] Generating new test snapshots (#6590)

* Test CDN mock is not re-assignable per test

* [skip ci] Generating new test snapshots (#6597)

* [skip ci] Generating new test snapshots (#6598)

* [skip ci] Generating new test snapshots (#6599)

* [skip ci] Generating new test snapshots (#6600)

* [skip ci] Generating new test snapshots (#6601)

* [skip ci] Generating new test snapshots (#6602)

* [skip ci] Generating new test snapshots (#6603)

* getWorkflow is signed

* add type parameter

* add response verification for CDN response

* remove workflows list

* add value to WorkflowTriggerAction

* step id

* hash and filerepo

* missingCdnHash

* linter and project

* fix project

* revert Package.resolved

* @unchecked Sendable

* use hash in generateOrGetCachedFileURL

* fix compilation

* skip responseVerificationMode in cdn

* change basePath of caches

* remove reserialization

* Use explicit type in GetWorkflowOperation.createFactory for greppability

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix swiftlint identifier_name violation in WorkflowDetailProcessorTests

Rename short variable `d` to `doubleValue` in two `if case .double(let d)`
patterns to satisfy the identifier_name rule requiring names >= 3 characters.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* remove default FileRepositoryType

* fix project

* fix test

* test preserves camel case

* Generating new test snapshots for `feat/workflows-network-layer` - ios-15 (#6654)

* Generating new test snapshots for `feat/workflows-network-layer` - ios-14 (#6656)

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Facundo Menzella <facumenzella@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Facundo Menzella <facumenzella@users.noreply.github.com>
2026-04-21 12:32:01 +02:00
Pol Miro a59ca8f4ea Expose apiKey on Purchases via @_spi(Internal) (#6635)
Adapter modules that import the SDK with `@_spi(Internal) import RevenueCat`
(e.g. `RevenueCatAdMob`) need to read the configured public API key when
constructing payloads such as the AdMob SSV `customRewardString`.

- Store the API key on `SystemInfo` and wire it through `Purchases` init.
- Add `@_spi(Internal) public var apiKey: String` on `Purchases`.
- Add a Swift API tester case so any future signature change is caught.
- Add a unit test verifying the accessor returns the configured key.

The key is already public plaintext in the app binary, so exposing it as SPI
does not introduce any new security risk.
2026-04-21 08:14:42 +02:00
Antonio PallaresandRevenueCat Git Bot f1d9fb86bb Send X-Installation-Method header in all API requests (#6431)
* Send X-Installation-Method header in all API requests

Detect at compile time which package manager was used to integrate the
SDK (SPM, CocoaPods, or prebuilt XCFramework) and send it as a new
X-Installation-Method header on every HTTP request. This helps the
backend understand how customers integrate the SDK.

Made-with: Cursor

* Add installation method assertions to installation tests

Expose installationMethod via @_spi(Internal) on Purchases and verify
the correct value in each installation test project (SPM, CocoaPods,
Carthage, Xcode direct, and XCFramework).

Made-with: Cursor

* [skip ci] Generating new test snapshots (#6433)

* [skip ci] Generating new test snapshots (#6435)

* [skip ci] Generating new test snapshots (#6434)

* [skip ci] Generating new test snapshots (#6440)

* [skip ci] Generating new test snapshots (#6436)

* [skip ci] Generating new test snapshots (#6437)

* [skip ci] Generating new test snapshots (#6438)

* [skip ci] Generating new test snapshots (#6439)

* [skip ci] Generating new test snapshots (#6443)

* Fix missing COCOAPODS_INSTALLATION flag on CocoaPods test targets

The flag was only set on the app target, not on the test targets, so
the #if COCOAPODS_INSTALLATION branches in InstallationTests.swift
were never compiled for CocoaPods tests. Add OTHER_SWIFT_FLAGS with
-DCOCOAPODS_INSTALLATION to all four CocoaPods test target configs.

Made-with: Cursor

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2026-03-12 12:05:14 +01:00
Rick 73c5534bf7 Fix reduced timeouts being used for HTTP requests when a proxy URL is configured (#6416) 2026-03-09 08:47:13 +01:00
Will Taylor 9356db1d42 [CEC Mode]: introduce isPurchaseAllowedByRestoreBehavior() (#6192) 2026-02-06 11:54:42 -06:00
5f9143563c Improve accuracy of transactions origin Part 8: sync cached local transaction metadata (#6073)
* Small cleanup

* add `LocalTransactionDetailsStorage`

* Add models for local transaction metadata caching. Reset PurchasesOrchestrator

* Complete `Codable`, lossless implementation of `LocalTransactionMetadata`

* Rename `LocalTransactionMetadataCache` to `LocalTransactionMetadataStore`

* Comment

* lint

* Remove unnecessary import

* Remove unused method

* Replace `Storefront` with `storeCountry` in both `ProductRequestData` and `PurchasedTransactionData`

This removes the need of a `StorefrontEncodedWrapper` object

* Disambiguate `asDictionary()` method

Now that `SubscriberAttribute` is `Codable`, `Encodable`'s `asDictionary()` and `SubscriberAttribute`'s `asDictionary()` were clashing

* Undo `Codable` conformance of `PresentedOfferingContext` and `TargetingContext`

* lint

* `LocalTransactionMetadata` now refers to a single transaction. `LocalTransactionMetadataStore` now stores one file per transaction and does not use an in-memory cache

* Temporarily remove `LocalTransactionMetadata` and `LocalTransactionMetadataStore` for easier PR review

* Revert "Temporarily remove `LocalTransactionMetadata` and `LocalTransactionMetadataStore` for easier PR review"

This reverts commit d958601711.

* Small code cleanup

* Remove `EncodedAppleReceipt` from `LocalTransactionMetadata`

* Undo `Codable` conformance of `EncodedAppleReceipt`

Not needed for now

* Remove `self.appTransactionJWS` from `LocalTransactionMetadata`

* Adapt to API changes in `SynchronizedLargeItemCache`

* Plug in `LocalTransactionMetadataStore` and store + get stored `LocalTransactionMetadata`

* Removed unused parameter

* Remove `schemaVersion` property from `LocalTransactionMetadata`

* Add `MockLocalTransactionMetadataStore` for tests

* Remove `appUserID` from `PurchasedTransactionData`

* Update tests

* Add `transaction_id` field to POST receipt

* adapt tests

* Add transaction ID parameter to cache key for `PostReceiptDataOperation`'s factory

* [skip ci] Generating new test snapshots (#6024)

* [skip ci] Generating new test snapshots (#6025)

* [skip ci] Generating new test snapshots (#6027)

* [skip ci] Generating new test snapshots (#6026)

* [skip ci] Generating new test snapshots (#6028)

* [skip ci] Generating new test snapshots (#6029)

* [skip ci] Generating new test snapshots (#6033)

* [skip ci] Generating new test snapshots (#6032)

* Fix lint

* Only send transaction ID when there's associated metadata

* Fix tests compilation

* Add unit test

* Add tests

* Add tests for `LocalTransactionMetadataStore`

* Have `PurchasesOrchestrator` post transaction with syncing purchases in SK2 go through `TransactionPoster` to include the `LocalTransactionMetadata` logic there

* Correct values for `purchaseCompletedBy` field in `PostReceiptDataOperation`

* Fix finish transaction logic

* Add more tests and fix test compilation

* More tests

* [skip ci] Generating new test snapshots (#6057)

* [skip ci] Generating new test snapshots (#6050)

* [skip ci] Generating new test snapshots (#6051)

* [skip ci] Generating new test snapshots (#6052)

* [skip ci] Generating new test snapshots (#6053)

* [skip ci] Generating new test snapshots (#6054)

* [skip ci] Generating new test snapshots (#6055)

* [skip ci] Generating new test snapshots (#6056)

* Fix lint

* Remove TODO

* Remove redundancy

* Fix tests and add test

* [skip ci] Generating new test snapshots (#6059)

* [skip ci] Generating new test snapshots (#6060)

* [skip ci] Generating new test snapshots (#6061)

* [skip ci] Generating new test snapshots (#6062)

* [skip ci] Generating new test snapshots (#6063)

* [skip ci] Generating new test snapshots (#6064)

* [skip ci] Generating new test snapshots (#6068)

* [skip ci] Generating new test snapshots (#6069)

* Add `transactionId` to `LocalTransactionMetadata`

* Add `getAllStoredMetadata()` method to `LocalTransactionMetadataStore`

* Cleanup stored metadata file if it fails to be read or decode

* Fix lint

* Simplify parameters in `handlePostReceiptResult` method in `PurchasesOrchestrator`

The same subscriber attributes were already included in the `PurchasedTransactionData` object

* Fix recovering `PresentedOfferingContext` from `LocalTransactionMetadata`

* Add `EncodedAppleReceipt` to `LocalTransactionMetadata`

* Take `source: PurchaseSource` out from `PurchasedTransactionData`

* Rename `PurchaseSource` to `PostReceiptSource` and `ProductRequestData.InitiationSource` to `PostReceiptSource.InitiationSource`

* Pass receipt as parameter directly

* Fix lint

* Remove unused variable

* Add internal interface to sync cached local transaction metadata

* Adapt unit tests

* Trigger cached transaction metadata sync on `applicationWillEnterForeground`

* fix test with previous value in snapshot

* Fix compilation of tests

* Introduce `sdk_originated` parameter in POST /receipt

* Adapt tests to new `sdkOriginated` property

* TEMP: Remove sdkOriginated field (to split into 2 PRs)

* Revert "TEMP: Remove sdkOriginated field (to split into 2 PRs)"

This reverts commit 6d361fde30.

* Remove sdkOriginated field as we won't be adding it for now

This reverts commit e4989a3d33.

* Store transaction metadata when offering context or paywall is present

* Fix PaywallEvent initialization in tests

* Use variable

* Cache CustomerInfo when receiving responses from cached transaction metadata syncs

* Add more tests

* Fix tests

* Move syncing of cached local metadata to `applicationDidBecomeActive`, which does happen on cold app launches

* Prevent concurrent cached transaction metadata syncs

* Add tests for applicationDidBecomeActive syncing cached transaction metadata

* Small improvements

* Perform sync in `applicationWillEnterForeground` + at `configure` time

* Fix tests after merge from main

* Fix and improved tests

* Fix tests

* test improvements

* Use `transactionId` in `PostData` as cacheKey only if it `containsAttributionData`

This means that POST /receipt for renewals are deduplicated, while purchases with attribution data are guaranteed to always be sent (regardless of whether there's an in-flight POST /receipt request for a renewal of that purchase)

* Adapt tests to new behavior + new tests

* Update Sources/Networking/Operations/PostReceiptDataOperation.swift

Co-authored-by: Toni Rico <toni.rico.diez@revenuecat.com>

* Do not clear `LocalTransactionMetadata` when receiving offline-computed CustomerInfo

* Add tests

* Fix test + add test

* Fix test

* Fix lint

* Fix test compilation

* Improve comment

* Fix codable `CodingKeys` to not use snake case in rawValues As the `JSONEncoder.default` uses `convertToSnakeCase` `keyEncodingStrategy`

This allows decoding using the `JSONDecoder.default (which uses `convertFromSnakeCase` `keyDecodingStrategy` to correctly decode the JSONs resulting from encoding with `JSONEncoder.default`.

* Add tests

* Improve comment

* Add `Codable` idempotency tests for `EncodedAppleReceipt`

* Add tests for encoding/decoding `LocalTransactionMetadata`

* Have `LocalTransactionMetadataStore` use a `.persistence` `DirectoryType` instead of a `.cache` one

* Add E2E tests for `LocalTransactionMetadataStore`

* Fix test

* Add some logs and reduce some flakiness of tests

* Remove test (will be added in a future PR after a small rewrite)

* Reduce test flakiness

* Change directory name

* Perform cached transaction metadata sync without delay on tests

* Remove unnecessary helper in tests

* Fix deadlock

* Inject `applicationSupportDirectory` to `LocalTransactionMetadataStore` for more reliable tests

* Fix lint

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
Co-authored-by: Toni Rico <toni.rico.diez@revenuecat.com>
2026-01-26 19:59:45 +01:00
Rick a01af9117b Added a swiftlint rule that disallows direct use of storage directory URL related APIs (#6113)
* Renamed applicationSupport directory type to persistence

* Only deleting the old diagnostics file when the new diagnostics file does not exist yet

* Implemented PR feedback

* Changed testing-only check from assertion to #if DEBUG

* Implemented migration + deleting LargeItemCache files from the Documents directory for Etags + DeviceCache caching

* Fixed compile issue after rebase

* Fixed test compilation after rebase

* Updated test

* Refactored logica to the specific classes that actually store the data, removing the logic from the large item cache

* Fix compilation issue

* Moved comment

* Implemented PR feedback

* Implemented most PR feedback

* Implemented PR feedback

* Simplified ETagManager's old Documents directory removal by just doing it on init if needed

* Added a swiftlint rule that disallows direct use of storage directory URL related APIs

* Fix compilation
2026-01-23 11:11:38 +01:00
Rick d3b845c8e5 Fix cache files visible in documents directory: Etags, offerings and product entitlements mapping (#6020)
* Renamed applicationSupport directory type to persistence

* Only deleting the old diagnostics file when the new diagnostics file does not exist yet

* Implemented PR feedback

* Changed testing-only check from assertion to #if DEBUG

* Implemented migration + deleting LargeItemCache files from the Documents directory for Etags + DeviceCache caching

* Fixed compile issue after rebase

* Fixed test compilation after rebase

* Updated test

* Refactored logica to the specific classes that actually store the data, removing the logic from the large item cache

* Fix compilation issue

* Moved comment

* Implemented PR feedback

* Implemented most PR feedback

* Implemented PR feedback

* Simplified ETagManager's old Documents directory removal by just doing it on init if needed

* Simplified old documents directory removal in EtagManager

* Also deleting old files from documents if we're clearing caches

* Fixed swiftlint warning

* Simplified directory cleanup between tests

* Updated FileRepository to keep using the existing directory in order to avoid duplicate cache files or having to migrate them right now

* Fixed tests not compiling

* Added additional test assertions that check whether new cache directory was created

* Add locking to DeviceCache migration logic to be safe

* Handle multiple concurrent reads across threads only actually migrating the data once

* PR feedback tweak
2026-01-22 17:17:50 +01:00
Antonio Pallares a226d36f7f Simplify SynchronizedLargeItemCache's key to use strings (#6012)
This will allow to easily query for all existing keys in a specific folder using `SynchronizedLargeItemCache`
2026-01-09 14:01:07 +01:00
Jacob Rakidzich c688108f44 UserDefaults Crash Fix (#5917)
* First pass–replace user defaults with file cache

* update tests and encoding mechanism

* Start on tests

* Wrap up tests

* clear for large item cache

* Migrate to a version of the cache that allows lookup by key instead of by index

* Mock cache is not used in this file, update it to the tailor made one just in case it's needed later
2025-12-22 12:21:21 +01:00
RickandRevenueCat Git Bot 94ac735467 Track connection_error_reason property in diagnostics for HTTP errors (#5860)
* Implemented initial HTTPRequestTimeoutManager + added first couple of tests

* Cleaned up the code and added a bunch more unit tests based on the Android test suite

* Updated doc format

* Add new files to workspace

* Added HTTPClient tests testing interaction with timeout manager

* Swiftlint fixes

* Updated comment

* Add missing file to workspace

* Fix after rebase

* Added extra HTTPClient <-> HTTPRequestTimeoutManager tests asserting on the recorded events

* Implemented PR feedback

* Fixed compile issue

* Fix compile issue

* Implemented PR feedback

* Removed deleted file reference from workspace

* Fixed test after changing reset timeout

* Make sure the default HTTPRequistTimeoutManager is using the default value from the HTTPClient

* Add a sophisticated test testing the full timeout flow against an unroutable IP for a real world scenario

* Updated timeout case name

* Fixed case where .timeoutOnMainBackendForFallbackSupportedEndpoint was also recorded for non timeouts and added tests to prevent regression

* Fixed only stubbing the HTTP response based on path, since that could be the same across hosts, resulting in flaky tests

* Implemented tracking ConnectionErrorReason using DiagnosticsTracker on HTTP errors

* Add new file to workspace

* Updated string value of ConnectionErrorReason cases to match Android implementation

* [skip ci] Generating new test snapshots (#5868)

* [skip ci] Generating new test snapshots (#5869)

* [skip ci] Generating new test snapshots (#5870)

* [skip ci] Generating new test snapshots (#5871)

* [skip ci] Generating new test snapshots (#5872)

* [skip ci] Generating new test snapshots (#5874)

* [skip ci] Generating new test snapshots (#5873)

* Updated the list of URLError.code's that we consider a network error

---------

Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2025-11-26 13:51:54 +01:00
Rick b49a054843 Add client side timeout logic for endpoints that support fallback URLs (#5760)
* Implemented initial HTTPRequestTimeoutManager + added first couple of tests

* Cleaned up the code and added a bunch more unit tests based on the Android test suite

* Updated doc format

* Add new files to workspace

* Added HTTPClient tests testing interaction with timeout manager

* Swiftlint fixes

* Updated comment

* Add missing file to workspace

* Fix after rebase

* Added extra HTTPClient <-> HTTPRequestTimeoutManager tests asserting on the recorded events

* Implemented PR feedback

* Fixed compile issue

* Fix compile issue

* Implemented PR feedback

* Removed deleted file reference from workspace

* Fixed test after changing reset timeout

* Make sure the default HTTPRequistTimeoutManager is using the default value from the HTTPClient

* Add a sophisticated test testing the full timeout flow against an unroutable IP for a real world scenario

* Updated timeout case name

* Fixed case where .timeoutOnMainBackendForFallbackSupportedEndpoint was also recorded for non timeouts and added tests to prevent regression

* Fixed only stubbing the HTTP response based on path, since that could be the same across hosts, resulting in flaky tests
2025-11-26 11:16:04 +01:00
Rosie Watson 8b229a2adc CC-582 | Allow for support ticket creation (#5779)
* feat: add contact support button and new sheet for ticket creation

* chore: use localisation

* feat: send support ticket details to backend

* feat: only show the support ticket creation button when config is set up

* feat: only show to correct customer type

* test: add base tests

* chore: remove unrequired var

* chore: use translations

* docs: update link to tuist

* refactor: move to cc api

* refactor: api calls

* test: update setup

* chore: better email validation

* chore: improved focus state

* chore: add dismiss

* chore: hide keyboard on dismiss

* chore: fix indentation

* feat: add charcter count

* chore: add rest of cc config

* test: clean up unit tests

* refactor: pull email validation out into struct

* chore: refine email checks

* refactor: pull out max characters into own var
2025-11-19 08:26:43 +00:00
d11c054407 Use cached offerings on network errors (#5707)
* Use offerings cache on (most) network errors

* Add unit tests for `NetworkError`'s `shouldFallBackToCachedOfferings`

* Add unit tests for `shouldFallBackToCachedOfferings`

* Fix lint

* Add some more unit tests

* Add `isLoadShedderResponse` and `isFallbackURLResponse` properties to `VerifiedHTTPResponse`

Keeps the values also when returned by the ETagManager

* lint

* Add some tests for ETagManager

* Rename `isFallbackURLResponse` to `isFallbackUrlResponse` to prevent decoding issues

* Add tests for actual source of original cached response of ETagManager

* Add tests to HTTPClientTests regarding the new booleans

* lint

* Add `originalSource` to `CustomerInfo`

* Adds `isLoadedFromCache` boolean to CustomerInfo

* Add docs

* Unit tests for new customer info properties

* Make `OriginalSource.CustomerInfo` a `String` enum

* Add decoding tests for Customer Info with new original source field

* Add `.loadShedder` check for Customer Info obtained in Load Shedder integration tests

* Update fixture

* improve internal docs

* Add intermediate object `Offerings.Contents` to wrap `OfferingsResponse` + `OriginalSource` and `loadedFromCache`

* Adapt existing unit tests to changes in `Offerings` underlying objects

* Check Offerings original source in existing integration tests

* Fix StoreKit unit tests

* Fix RevenueCatUI tests

* More Offerings.Contents tests

* Fix test

* Add more tests

* Fix lint

* [skip ci] Generating new test snapshots (#5741)

* [skip ci] Generating new test snapshots (#5742)

* [skip ci] Generating new test snapshots (#5743)

* [skip ci] Generating new test snapshots (#5744)

* [skip ci] Generating new test snapshots (#5745)

* [skip ci] Generating new test snapshots (#5746)

* [skip ci] Generating new test snapshots (#5747)

* [skip ci] Generating new test snapshots (#5748)

* Use enum for `HTTPResponseSource`

* Update tests

* Adapt to changes in `VerifiedHTTPResponse`

* Lint

* Adapt to changes in `VerifiedHTTPResponse`

* update tests

* Add log when a request to the fallback URL was handled by load shedder (which should never happen)

* rename `HTTPResponseSource` to `HTTPResponseOriginalSource`

* Adapt to changes

* fix lint

* Adapt to changes

* Fix CustomerInfo's OriginalSource implementation + fix unit test

* Fix tests compilation

* Add Cached offerings integration test

* Fix RCUI compilation

* Move isFromCache boolean from `Offerings.Contents` to `Offerings`

* Expand `ForceServerErrorStrategy` functionality

* Improve log when faking error response

* Correct implementation of fake error response without making a request (ForceServerErrorStrategy)

* Update tests + more tests

* Fix compilation of `OfferingsManagerTests`

* Fix compilation of `DebugViewSwiftUITests`

* Improve tests

* Fix `OfflineWithNoMappingStoreKitIntegrationTests`

* FIx compilation

---------

Co-authored-by: Toni Rico <toni.rico.diez@revenuecat.com>
Co-authored-by: RevenueCat Git Bot <72824662+RCGitBot@users.noreply.github.com>
2025-11-07 10:22:16 +00:00
Antonio Pallares eaee0c3592 Fix signature verification fallback urls (#5756)
* Fix signature verification for fallback URLs

* Add tests for signing with fallback path

* Lint

* Add log
2025-11-06 22:43:27 +01:00
Antonio Pallares 6335078c13 Add backend source to VerifiedHTTPResponse (#5736)
* Add `isLoadShedderResponse` and `isFallbackURLResponse` properties to `VerifiedHTTPResponse`

Keeps the values also when returned by the ETagManager

* lint

* Add some tests for ETagManager

* Rename `isFallbackURLResponse` to `isFallbackUrlResponse` to prevent decoding issues

* Add tests for actual source of original cached response of ETagManager

* Add tests to HTTPClientTests regarding the new booleans

* lint

* Use enum for `HTTPResponseSource`

* Update tests

* Add log when a request to the fallback URL was handled by load shedder (which should never happen)

* rename `HTTPResponseSource` to `HTTPResponseOriginalSource`

* fix lint
2025-11-04 20:17:33 +01:00
Rick 72cf38a0fe Added an internal API for overriding the API base URL (#5739)
* Added an internal API for overriding the API base URL

* Updated and added tests for API baseURL configuration option

* Revert change that removed serverHostURL from HTTPRequestPath since it broke other types implementing this protocol

* swiftlint

* Removed the apiBaseURL property from Purchases since it's only used for internal testing anyways

* Remove unused @_spi(Internal)

* Updated comment on api base URL vs proxy URL

* Fixed linting issue
2025-11-04 13:35:20 +01:00
Pol Miro 2658f2b8fa Refactor: Rename PaywallEventsManager to EventsManager and separate ad events (#5718)
* Rename paywallsEventsManager to eventsManager

* Rename PaywallEventsManagerType to EventsManagerType

* Rename PaywallEventsManager to EventsManager

* Rename PaywallEventStore to FeatureEventStore

* Rename InternalAPI.postPaywallEvents to postFeatureEvents

* Rename StoredEventSerializer to StoredFeatureEventSerializer

* Rename createStoredEvent to createFeatureStoredEvent

* Rename StoredEvent to StoredFeatureEvent

* Rename HTTPRequest.PaywallPath to HTTPRequest.FeatureEventsPath

* Rearrange events files

* Rename event related files

* Extract shared events endpoint configuration to EventsHTTPRequestPath

Both FeatureEventsPath and AdPath share the same /v1/events endpoint
configuration, differing only in domain (api-paywalls.revenuecat.com vs
a.revenue.cat) and name. Extract common logic to EventsHTTPRequestPath
protocol in Sources/Events/Networking.

* Move Sources/FeatureEvents to Sources/Events/FeatureEvents

* Rename EventsRequest to FeatureEventsRequest

- Rename EventsRequest.swift to FeatureEventsRequest.swift
- Move file to Sources/Events/FeatureEvents/Networking/
- Update all references in source and test files
- Update Xcode project file references

This makes it clear that this request type is specifically for the
feature events endpoint, not a generic events request.

* Remove ad events from feature events system

Ad events should not be sent through the feature events system as they
require their own separate infrastructure with a different API endpoint.

Changes:
- Remove FeatureEvent conformance from AdEvent
- Remove .ads case from Feature enum
- Remove ad events handling from FeatureEventsRequest
- Add no-op track(adEvent:) method to EventsManager with comment
- Update AdTracker to call the new track(adEvent:) method

Ad events tracking now becomes a no-op until proper implementation with:
- StoredAdEvent structure
- AdEventStore for persistence
- InternalAPI.postAdEvents() using HTTPRequest.AdPath.postEvents

* Rename PostEventsOperation to PostFeatureEventsOperation

- Rename PostEventsOperation.swift to PostFeatureEventsOperation.swift
- Move file to Sources/Events/FeatureEvents/Networking/
- Update class name and remove misleading "generic" comment
- Update references in InternalAPI.swift
- Update Xcode project file references

This makes it clear that this operation is specifically for posting
feature events, not a generic operation for various event types.
2025-10-30 14:52:35 +01:00
Antonio Pallares 3ace587482 [SDK-4153] Use static fallback urls (#5709)
* change fallback URL logic to support a different path from the main server

* Adapt unit tests to changes in fallback urls logic

* lint

* Add unit test for fallback urls

* fix switched logic
2025-10-29 18:43:19 +01:00
Pol MiroandClaude 470ce93f4f Add non paid revenue reporting infra (#5640)
* Add RC Ads event tracking infrastructure

Implements event tracking for RevenueCat Ads following the Paywalls Events pattern.

- Adds three event types: ad displayed, ad opened, and ad revenue
- Uses actor-based concurrency with file-based event storage
- Posts events to e.revenue.cat/v1/events endpoint
- Marks track(adEvent:) method as @_spi(Internal) for internal use
- Includes comprehensive unit tests with snapshot testing
- Available on iOS 15.0+, tvOS 15.0+, macOS 12.0+, watchOS 8.0+

Event schema follows khepri RC Ads input events specification with
app_session_id field matching backend expectations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Avoid mapping in EventsRequest+Ad

* Consolidate ad events into PaywallEventsManager

Eliminates duplication between AdEventsManager and PaywallEventsManager by:
- Making PaywallEventsManager handle all event types (ads, paywalls, customerCenter)
- Adding feature-aware routing in flushEvents() to send events to correct domains
  - Ad events → https://e.revenue.cat/v1/events
  - Other events → https://api-paywalls.revenuecat.com/v1/events
- Removing AdEventsManager, AdEventStore, and their tests (~500 lines)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Remove AdsStrings and use PaywallsStrings instead

AdsStrings only had 2 strings in use, both of which already exist in PaywallsStrings. Consolidates logging strings to eliminate duplication.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Namespace Precision enum inside AdEvent.RevenueData

Moves Precision from a top-level public enum to AdEvent.RevenueData.Precision to avoid polluting the global namespace and reduce autocomplete noise.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Move Precision conformances to end of file

Follows the pattern of other types by declaring protocol conformances at the end of the file rather than inline with the type definition.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Remove redundant sessionIdentifier from AdImpressionData

The sessionIdentifier field in AdImpressionData was redundant since
StoredEvent already tracks appSessionID. This change:

- Removes sessionIdentifier from AdImpressionData struct
- Uses storedEvent.appSessionID directly when building requests
- Renames sessionId to appSessionId to match backend field app_session_id
- Updates documentation examples to remove sessionIdentifier parameter
- Adds guard statement for optional appSessionID
- Updates all test fixtures and regenerates snapshots
- Removes iOS26 snapshot references from project

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Remove unneeded SessionId

* Add proper assertions to PurchasesAdEventsTests

Enhanced test coverage for public ad tracking APIs:
- Verify events are tracked via mockPaywallEventsManager
- Assert correct event types (displayed, opened, revenue)
- Validate all impression data fields
- Verify revenue-specific fields (revenueMicros, currency, precision)

All 3 tests now pass with proper verification.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add ENABLE_AD_EVENTS_TRACKING compiler flag

* Simplify track ad events APIs

* Fix ENABLE_AD_EVENTS_TRACKING scope and refactor Precision to struct

Compiler flag fixes:
- Move ENABLE_AD_EVENTS_TRACKING #endif to wrap all ad event code including internal enum
- Add compiler flag guards to all three test files

Precision API refactor:
- Change AdRevenue.Precision from enum to struct following Apple's API patterns (like Message.Reason)
- Use internal init(rawValue:) to prevent custom precision values
- Convert enum cases to static properties maintaining same public API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Refactor mediatorName from String to MediatorName struct

Replace string-based mediator names with a type-safe struct following Apple's API patterns:
- Add MediatorName struct with public init(rawValue:) to support custom values
- Include predefined static properties for .adMob and .appLovin
- Update AdEventData protocol to require MediatorName type
- Update all event types (AdDisplayed, AdOpened, AdRevenue) to use MediatorName
- Use .rawValue when serializing to network requests
- Update all tests and documentation examples to use .appLovin

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Remove RawRepresentable conformance from Precision and update test snapshots

- Remove RawRepresentable conformance from AdRevenue.Precision to allow internal init
- Update test assertions to use .appLovin instead of string comparison
- Update all snapshot test files to use "AppLovin" instead of "MAX"
- All ad event tests now passing (11/11)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix PaywallDataDecodingTests locale check for region overrides

The test was failing when the system locale included region overrides
(e.g., "en_US@rg=eszzzz" instead of just "en_US").

Changes:
- Use beginWith("en_US") instead of exact equality check
- Compare against enConfig directly instead of fetching via Locale.current

This makes the test more robust while maintaining the same behavior validation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Rename timestampMs to timestamp but keep serialized timestamp_ms

* Use different serverHostURL

* Simplify and paralelize postEvents

* Adjust usage of ENABLE_AD_EVENTS_TRACKING flag

* Move track ad event methods to AdTracker

* Remove PaywallEventsManager implementation

* Improving naming overlapping naming AdEvent->AdEventRequest

* Simplify compiler flag usage

* Use Experimental

* Remove duplicate with PostPaywallEventsOperation and PostAdEventsOperation

* Remove postAdEvents methods assuming reuse of event storage

* Make Precision rawValue internal

* Remove runtime checks

* Trigger build

* Move Public Types MARK comment after internal protocol

* Add documentation for AdDisplayed, AdOpened, and AdRevenue properties

* Remove redundant smoke tests

The "DoesNotCrash" tests were completely redundant with the
comprehensive "StoresEvent" tests. The comprehensive tests already:
1. Verify methods don't crash (implicitly)
2. Verify events are stored
3. Verify event data is correct

Removed 3 redundant tests, keeping only the 3 comprehensive tests.

* Fix bug not tracking initialized events

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-29 11:56:48 +01:00