From 7c952de992cf205d7e9c92b8e1a141b22166ba7e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 13 Oct 2026 13:05:45 +0000 Subject: [PATCH] Dedupe setAppUserId identify posts for SDK 0.3.3 Skip /ingestIdentify when the app user id matches the last successful identify (persisted like trackInstall), coalesce concurrent identical calls, type optional redeem codeMatches and offer.creatorName, and bump to 0.3.3. Co-authored-by: Kenny Ye --- CHANGELOG.md | 6 ++ PUBLISHING.md | 4 +- README.md | 12 ++-- __tests__/tapAppLink.test.ts | 133 ++++++++++++++++++++++++++++++++++- package-lock.json | 4 +- package.json | 2 +- src/index.ts | 1 + src/storage.ts | 4 ++ src/tapAppLink.ts | 73 ++++++++++++++++--- 9 files changed, 218 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9671f7..d04c0a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.3.3 + +- **Fixed:** `setAppUserId` posted `/ingestIdentify` on every call, so apps that link the billing user id from several places (for example Keep Maps) could fire it three times per launch. 0.3.3 skips when the id matches the last successfully identified value (persisted like `trackInstall`), and coalesces concurrent identical calls into one request. A different id still posts. +- Add optional `codeMatches` and `offer.creatorName` on the typed `TapAppLinkRedeemResult` from `applyCode` (matches server redeem response fields). +- Send `X-TapAppLink-SDK-Version: 0.3.3` on all requests. + ## 0.3.2 - **Fixed:** retrying `applyCode` after a timeout could count an install twice. 0.3.2 sends a request ID so the server recognises the retry. No code changes needed. diff --git a/PUBLISHING.md b/PUBLISHING.md index 2570cb0..e645767 100644 --- a/PUBLISHING.md +++ b/PUBLISHING.md @@ -34,8 +34,8 @@ No repo secret is required for Option A. The release workflow already sets `perm 3. Tag that commit and push: ```bash -git tag v0.3.2 -git push origin v0.3.2 +git tag v0.3.3 +git push origin v0.3.3 ``` Do not retag an old commit with a new version name. The publish job checks that `v*` equals `package.json` version on the tagged commit. diff --git a/README.md b/README.md index a6eee1d..40e16bb 100644 --- a/README.md +++ b/README.md @@ -6,19 +6,19 @@ Works in Expo **dev clients and production builds**. Expo Go cannot load the And ## Install -Install **0.3.2 or later** of the SDK, together with AsyncStorage. AsyncStorage is required so install state survives cold launches; without it each launch can post a new install. +Install **0.3.3 or later** of the SDK, together with AsyncStorage. AsyncStorage is required so install state survives cold launches; without it each launch can post a new install. **Expo** ```bash -npx expo install @tapapplink/react-native@0.3.2 @react-native-async-storage/async-storage +npx expo install @tapapplink/react-native@0.3.3 @react-native-async-storage/async-storage ``` **Bare React Native** ```bash -npm install @tapapplink/react-native@0.3.2 @react-native-async-storage/async-storage -# or: yarn add @tapapplink/react-native@0.3.2 @react-native-async-storage/async-storage +npm install @tapapplink/react-native@0.3.3 @react-native-async-storage/async-storage +# or: yarn add @tapapplink/react-native@0.3.3 @react-native-async-storage/async-storage ``` Bare React Native iOS apps should run `cd ios && pod install` after installing. @@ -49,7 +49,7 @@ await TapAppLink.setAppUserId(await Purchases.getAppUserID()); const offer = TapAppLink.getOffer(); ``` -`trackInstall` posts `/ingestInstall` once per install (keyed by a persisted `installId`). Later launches restore the stored attribution id and offer without posting again. `setAppUserId` sends that stored `attributionId` after hydrate. +`trackInstall` posts `/ingestInstall` once per install (keyed by a persisted `installId`). Later launches restore the stored attribution id and offer without posting again. `setAppUserId` sends that stored `attributionId` after hydrate, posts `/ingestIdentify` only when the app user id changes, and coalesces concurrent identical calls. Set `debug: true` to log each request, response and stored state. The API key is redacted in those logs. @@ -59,7 +59,7 @@ Purchases are attributed with billing **webhooks**, not a client `trackPurchase` Show success only when `applyCode` resolves. Map each result to UI state as below. Customers must never see the word "environment". -On a `network` (or timeout) error only, retry `applyCode` once with the same code. Do not auto-retry `unknownCode`, `inactiveCode`, or `wrongEnvironment`. If that retry also fails, show N6 ("We couldn't check your code. Check your connection and try again.") with a **Try again** button. From 0.3.2, that automatic retry is safe because the SDK reuses its request ID, so the server will not count the install twice. +On a `network` (or timeout) error only, retry `applyCode` once with the same code. Do not auto-retry `unknownCode`, `inactiveCode`, or `wrongEnvironment`. If that retry also fails, show N6 ("We couldn't check your code. Check your connection and try again.") with a **Try again** button. From 0.3.2, that automatic retry is safe because the SDK reuses its request ID, so the server will not count the install twice. From 0.3.3, success results may include optional `codeMatches` and `offer.creatorName`. ```ts type RedeemUi = { diff --git a/__tests__/tapAppLink.test.ts b/__tests__/tapAppLink.test.ts index 18dc4fc..e6c6e59 100644 --- a/__tests__/tapAppLink.test.ts +++ b/__tests__/tapAppLink.test.ts @@ -63,8 +63,8 @@ describe("TapAppLink", () => { const headers = (fetchMock.mock.calls[0][1] as { headers: Record }) .headers; - expect(headers["X-TapAppLink-SDK-Version"]).toBe("0.3.2"); - expect(SDK_VERSION).toBe("0.3.2"); + expect(headers["X-TapAppLink-SDK-Version"]).toBe("0.3.3"); + expect(SDK_VERSION).toBe("0.3.3"); }); it("tracks install once, sends installId, and caches offer", async () => { @@ -182,6 +182,132 @@ describe("TapAppLink", () => { }); }); + it("skips ingestIdentify when appUserId matches the last successful identify", async () => { + const fetchMock = jest + .fn() + .mockResolvedValueOnce(jsonResponse(200, { attributionId: "attr_id" })) + .mockResolvedValueOnce(jsonResponse(200, { ok: true })); + global.fetch = fetchMock as unknown as typeof fetch; + + configure(); + await TapAppLink.trackInstall(); + const first = await TapAppLink.setAppUserId("user_same"); + const second = await TapAppLink.setAppUserId("user_same"); + + expect(first).toMatchObject({ ok: true }); + expect(second).toMatchObject({ + skipped: true, + appUserId: "user_same", + attributionId: "attr_id", + }); + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(asyncStore.get(STORAGE_KEY)).toContain("user_same"); + }); + + it("does not post ingestIdentify again after a cold start with the same appUserId", async () => { + const fetchMock = jest + .fn() + .mockResolvedValueOnce(jsonResponse(200, { attributionId: "attr_cold_id" })) + .mockResolvedValueOnce(jsonResponse(200, { ok: true })); + global.fetch = fetchMock as unknown as typeof fetch; + + configure(); + await TapAppLink.trackInstall(); + await TapAppLink.setAppUserId("user_persisted"); + expect(fetchMock).toHaveBeenCalledTimes(2); + + const persisted = asyncStore.get(STORAGE_KEY); + expect(persisted).toContain("user_persisted"); + await TapAppLink.resetForTesting(); + asyncStore.set(STORAGE_KEY, persisted!); + + configure(); + const resumed = await TapAppLink.setAppUserId("user_persisted"); + + expect(fetchMock).toHaveBeenCalledTimes(2); + expect(resumed).toMatchObject({ + skipped: true, + appUserId: "user_persisted", + attributionId: "attr_cold_id", + }); + expect(TapAppLink.getAppUserId()).toBe("user_persisted"); + }); + + it("coalesces concurrent identical setAppUserId calls into one POST", async () => { + let resolveIdentify: ((value: unknown) => void) | undefined; + const identifyGate = new Promise((resolve) => { + resolveIdentify = resolve; + }); + const fetchMock = jest.fn().mockImplementation(async (url: string) => { + if (String(url).includes("/ingestIdentify")) { + await identifyGate; + return jsonResponse(200, { ok: true }); + } + return jsonResponse(200, { attributionId: "attr_race" }); + }); + global.fetch = fetchMock as unknown as typeof fetch; + + configure(); + await TapAppLink.trackInstall(); + + const a = TapAppLink.setAppUserId("user_race"); + const b = TapAppLink.setAppUserId("user_race"); + const c = TapAppLink.setAppUserId("user_race"); + resolveIdentify?.(undefined); + const results = await Promise.all([a, b, c]); + + expect(results[0]).toEqual(results[1]); + expect(results[1]).toEqual(results[2]); + expect(results[0]).toMatchObject({ ok: true }); + const identifyCalls = fetchMock.mock.calls.filter((call) => + String(call[0]).includes("/ingestIdentify"), + ); + expect(identifyCalls).toHaveLength(1); + }); + + it("posts ingestIdentify again when appUserId changes", async () => { + const fetchMock = jest + .fn() + .mockResolvedValueOnce(jsonResponse(200, { attributionId: "attr_change" })) + .mockResolvedValueOnce(jsonResponse(200, { ok: true })) + .mockResolvedValueOnce(jsonResponse(200, { ok: true })); + global.fetch = fetchMock as unknown as typeof fetch; + + configure(); + await TapAppLink.trackInstall(); + await TapAppLink.setAppUserId("user_a"); + await TapAppLink.setAppUserId("user_b"); + + expect(fetchMock).toHaveBeenCalledTimes(3); + const secondIdentify = JSON.parse( + (fetchMock.mock.calls[2][1] as { body: string }).body, + ) as { appUserId: string }; + expect(secondIdentify.appUserId).toBe("user_b"); + expect(TapAppLink.getAppUserId()).toBe("user_b"); + expect(asyncStore.get(STORAGE_KEY)).toContain("user_b"); + expect(asyncStore.get(STORAGE_KEY)).not.toContain("user_a"); + }); + + it("does not skip identify after a failed ingestIdentify", async () => { + const fetchMock = jest + .fn() + .mockResolvedValueOnce(jsonResponse(200, { attributionId: "attr_fail" })) + .mockResolvedValueOnce(jsonResponse(500, { message: "identify failed" })) + .mockResolvedValueOnce(jsonResponse(200, { ok: true })); + global.fetch = fetchMock as unknown as typeof fetch; + + configure(); + await TapAppLink.trackInstall(); + await expect(TapAppLink.setAppUserId("user_retry")).rejects.toThrow( + "identify failed", + ); + const retry = await TapAppLink.setAppUserId("user_retry"); + + expect(retry).toMatchObject({ ok: true }); + expect(fetchMock).toHaveBeenCalledTimes(3); + expect(asyncStore.get(STORAGE_KEY)).toContain("user_retry"); + }); + it("does not treat a non-2xx ingest response as success", async () => { const fetchMock = jest.fn().mockResolvedValue( jsonResponse(500, { @@ -249,6 +375,7 @@ describe("TapAppLink", () => { jsonResponse(200, { attributionId: "attr_applied", alreadyAttributed: false, + codeMatches: true, offer: { creatorName: "Ada", promoCode: "ADA10", @@ -263,6 +390,8 @@ describe("TapAppLink", () => { expect(result).toMatchObject({ attributionId: "attr_applied", alreadyAttributed: false, + codeMatches: true, + offer: { creatorName: "Ada" }, }); expect(TapAppLink.getOffer()?.creatorName).toBe("Ada"); expect(TapAppLink.getAttributionId()).toBe("attr_applied"); diff --git a/package-lock.json b/package-lock.json index 3c9ff08..e5d73d8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@tapapplink/react-native", - "version": "0.3.2", + "version": "0.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@tapapplink/react-native", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "devDependencies": { "@react-native-async-storage/async-storage": "^2.2.0", diff --git a/package.json b/package.json index e85dfbd..7b6665c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tapapplink/react-native", - "version": "0.3.2", + "version": "0.3.3", "description": "Tap App Link attribution SDK for React Native and Expo", "license": "MIT", "homepage": "https://tapapplink.com", diff --git a/src/index.ts b/src/index.ts index 0faa072..187bac8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,7 @@ export { type TapAppLinkEnvironment, type TapAppLinkOffer, type TapAppLinkRedeemErrorCode, + type TapAppLinkRedeemResult, } from "./tapAppLink"; export type { PersistedInstallState } from "./storage"; export { TapAppLink as default } from "./tapAppLink"; diff --git a/src/storage.ts b/src/storage.ts index 618a6d8..095f719 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -7,6 +7,8 @@ export type PersistedInstallState = { installId: string; tracked: boolean; attributionId?: string; + /** Last app user id that successfully completed `/ingestIdentify`. */ + appUserId?: string; offer?: { creatorName: string; promoCode: string | null; @@ -96,6 +98,8 @@ export const loadInstallState = async ( typeof parsed.attributionId === "string" ? parsed.attributionId : undefined, + appUserId: + typeof parsed.appUserId === "string" ? parsed.appUserId : undefined, offer: parsed.offer ?? null, pendingRedeem, }; diff --git a/src/tapAppLink.ts b/src/tapAppLink.ts index 157b71c..bb8374e 100644 --- a/src/tapAppLink.ts +++ b/src/tapAppLink.ts @@ -12,7 +12,7 @@ import { } from "./storage"; /** Sent as `X-TapAppLink-SDK-Version` on every request. */ -export const SDK_VERSION = "0.3.2"; +export const SDK_VERSION = "0.3.3"; export type TapAppLinkEnvironment = "production" | "sandbox"; @@ -22,6 +22,22 @@ export type TapAppLinkOffer = { billingOfferId: string | null; }; +/** + * Success body from `/redeemCode`. New fields from the server are optional so + * older clients keep type-checking. + */ +export type TapAppLinkRedeemResult = { + attributionId?: string; + alreadyAttributed?: boolean; + /** True when the submitted code matches the attributed creator offer. */ + codeMatches?: boolean; + offer?: { + creatorName?: string; + promoCode?: string | null; + billingOfferId?: string | null; + } | null; +}; + export type TapAppLinkConfig = { publicKey: string; environment: TapAppLinkEnvironment; @@ -129,8 +145,12 @@ let installId: string | undefined; let tracked = false; let lastAttributionId: string | undefined; let lastAppUserId: string | undefined; +/** Last app user id that successfully completed `/ingestIdentify` (persisted). */ +let identifiedAppUserId: string | undefined; let lastOffer: TapAppLinkOffer | null = null; let pendingRedeem: PendingRedeemState | null = null; +/** Coalesce concurrent identical `setAppUserId` calls into one POST. */ +const identifyInFlight = new Map>>(); /** Uppercase, strip non-alphanumerics, max 24 chars. Used only for requestId reuse. */ const normaliseRedeemCode = (code: string): string => @@ -164,12 +184,16 @@ const applyPersisted = (state: PersistedInstallState) => { installId = state.installId; tracked = state.tracked; lastAttributionId = state.attributionId; + identifiedAppUserId = state.appUserId; + if (state.appUserId) { + lastAppUserId = state.appUserId; + } lastOffer = state.offer ?? null; pendingRedeem = state.pendingRedeem ?? null; }; const persist = async () => { - if (!installId && !pendingRedeem) return; + if (!installId && !pendingRedeem && !identifiedAppUserId) return; if (!installId) { installId = createInstallId(); } @@ -177,6 +201,7 @@ const persist = async () => { installId, tracked, attributionId: lastAttributionId, + ...(identifiedAppUserId ? { appUserId: identifiedAppUserId } : {}), offer: lastOffer, ...(pendingRedeem ? { pendingRedeem } : {}), }; @@ -185,6 +210,7 @@ const persist = async () => { installId: state.installId, tracked: state.tracked, attributionId: state.attributionId, + appUserId: state.appUserId, offer: state.offer, pendingRedeem: state.pendingRedeem ?? null, }); @@ -387,13 +413,42 @@ export const TapAppLink = { setAppUserId: async (appUserId: string) => { await ensureHydrated(); lastAppUserId = appUserId; - return post("/ingestIdentify", { - appUserId, - attributionId: lastAttributionId, - }); + + if (identifiedAppUserId === appUserId) { + const skipped = { + skipped: true as const, + appUserId, + attributionId: lastAttributionId, + }; + debugLog("setAppUserId skipped; already identified", skipped); + return skipped; + } + + const existing = identifyInFlight.get(appUserId); + if (existing) { + debugLog("setAppUserId coalesced with in-flight identify", { appUserId }); + return existing; + } + + const promise = (async (): Promise> => { + try { + const result = await post("/ingestIdentify", { + appUserId, + attributionId: lastAttributionId, + }); + identifiedAppUserId = appUserId; + await persist(); + return result; + } finally { + identifyInFlight.delete(appUserId); + } + })(); + + identifyInFlight.set(appUserId, promise); + return promise; }, - applyCode: async (code: string) => { + applyCode: async (code: string): Promise => { await ensureHydrated(); const normalisedCode = normaliseRedeemCode(code); let requestId: string; @@ -419,7 +474,7 @@ export const TapAppLink = { cacheFromResult(result); pendingRedeem = null; await persist(); - return result; + return result as TapAppLinkRedeemResult; } catch (error) { const mapped = mapRedeemError(error); if (isDefinitiveRedeemError(mapped.code)) { @@ -449,9 +504,11 @@ export const TapAppLink = { installId = undefined; lastAttributionId = undefined; lastAppUserId = undefined; + identifiedAppUserId = undefined; lastOffer = null; pendingRedeem = null; hydratePromise = null; + identifyInFlight.clear(); await clearInstallState(storage); resetStorageHelpersForTesting(); storage = resolveStorage();