Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
# Changelog

## 0.2.0

Adopts the native **0.2.0** SDKs. All four LinkTrail SDKs (iOS, Android, React Native, Flutter)
now share one version.

### Changed
- Native pins: iOS `LinkTrailSDK ~> 0.2.0` (from `~> 0.1.0`) and Android `io.linktrail:sdk:0.2.0`
(from `0.1.0`). The example app builds against the same pins.
- iOS now reports the wrapper in the `X-LinkTrail-SDK` header (`react-native/0.2.0`), as Android
already did.

### Added
- Error code `invalidEvent`, with the rejected `reason` (string) on the error and on `onError`
events. `trackEvent` reports it when the name is blank, the `value` is NaN, infinite or
negative, or the `currency` isn't 3 letters, and sends nothing. The message is the native one
(`Invalid event: <reason>`).

### Removed
- **Breaking:** `error.legacyCode` and the `LinkTrailLegacyErrorCode` type (deprecated in 0.1.1).
Use `error.code`. Snake_case codes from native are no longer translated; they map to `unknown`.

## 0.1.1

Implements [wrapper parity 0.1.1](https://github.com/linktrail-io/workspace/blob/main/contracts/wrapper-parity-0.1.1.md).
Expand Down
2 changes: 1 addition & 1 deletion LinktrailReactNative.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Pod::Spec.new do |s|

# The binary LinkTrail iOS SDK, published to the CocoaPods trunk — CocoaPods
# resolves it automatically, so the consuming app needs no extra Podfile line.
s.dependency "LinkTrailSDK", "~> 0.1.0"
s.dependency "LinkTrailSDK", "~> 0.2.0"

s.pod_target_xcconfig = {
"DEFINES_MODULE" => "YES",
Expand Down
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,14 @@ Every promise rejects with a `LinkTrailError`, and `onError` gets the same field

| Field | |
| --- | --- |
| `code` | `missingApiKey`, `invalidApiKey`, `notConfigured`, `invalidUrl`, `notALinkTrailUrl`, `transport`, `server`, `decoding`, `emptyResponse`, `invalidArgument`, `unknown` |
| `code` | `missingApiKey`, `invalidApiKey`, `notConfigured`, `invalidUrl`, `notALinkTrailUrl`, `transport`, `server`, `decoding`, `emptyResponse`, `invalidArgument`, `invalidEvent`, `unknown` |
| `message` | The native SDK's message, unchanged |
| `statusCode`, `body` | `server` errors only (`body` when the server sent one) |
| `legacyCode` | The pre-0.1.1 snake_case code. Deprecated; removed in the next minor release |
| `reason` | `invalidEvent` errors only: why the event was rejected, e.g. `name is blank` |

`trackEvent` rejects with `invalidEvent` (and reports it to `onError`) when the name is blank, the
`value` is NaN, infinite or negative, or the `currency` isn't 3 letters. Nothing is sent. The rules
come from the native SDK; this package adds none of its own.

```ts
try {
Expand All @@ -103,8 +107,8 @@ const attribution = await LinkTrail.getLastAttribution();
const lastLink = await LinkTrail.getLastDeepLink();

// Versions: this package, and the embedded native SDK.
LinkTrail.version; // "0.1.1"
LinkTrail.nativeSdkVersion; // e.g. "0.1.0"
LinkTrail.version; // "0.2.0"
LinkTrail.nativeSdkVersion; // e.g. "0.2.0"

// iOS ATT / SKAdNetwork. On Android there is no ATT: requestTrackingAuthorization()
// is not applicable and resolves `true` (the OS does not restrict tracking); the
Expand Down
2 changes: 0 additions & 2 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ describe('configure', () => {
mockNative.configure.mockRejectedValue(err);
await expect(api.LinkTrail.configure('')).rejects.toMatchObject({
code: 'missingApiKey',
legacyCode: 'missing_api_key',
message: 'blank',
});
expect(Linking.addEventListener).not.toHaveBeenCalled();
Expand Down Expand Up @@ -220,7 +219,6 @@ describe('event emitters', () => {
emit({ code: 'transport', message: 'offline' });
expect(listener).toHaveBeenCalledWith({
code: 'transport',
legacyCode: 'transport',
message: 'offline',
});
s.remove();
Expand Down
106 changes: 106 additions & 0 deletions __tests__/native-bridges.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/* eslint-env jest */
// Source checks for the native bridges (Kotlin / Swift), which Jest can't run: error-code
// mapping, error details, the iOS SDK header call, and the native pins.
import { readFileSync } from 'fs';
import { join } from 'path';

const read = (path: string) =>
readFileSync(join(__dirname, '..', path), 'utf8');
const pkg = require('../package.json') as { version: string };

const kotlin = read(
'android/src/main/java/io/linktrail/reactnative/LinkTrailModule.kt',
);
const swift = read('ios/LinkTrailModuleImpl.swift');

/** The body of a Kotlin `fun name(...)` or Swift `func name(...)`, up to the next declaration. */
function body(source: string, name: string): string {
const start = source.search(new RegExp(`\\bfunc? ${name}\\(`));
expect(start).toBeGreaterThanOrEqual(0);
const rest = source.slice(start + 1);
const next = rest.search(
/\n {2}(?:@objc |private |public |override |static )*(?:func?|val|var) /,
);
return next < 0 ? rest : rest.slice(0, next);
}

describe('Android bridge', () => {
it('maps LinkTrailError.InvalidEvent to invalidEvent, before the unknown fallback', () => {
const mapping = body(kotlin, 'errorCode');
expect(mapping).toMatch(
/is LinkTrailError\.InvalidEvent -> "invalidEvent"/,
);
expect(mapping.indexOf('InvalidEvent')).toBeLessThan(
mapping.indexOf('else -> "unknown"'),
);
});

it('passes reason for InvalidEvent in the error details (reject + onError)', () => {
const details = body(kotlin, 'errorDetails');
expect(details).toMatch(
/is LinkTrailError\.InvalidEvent -> [\s\S]*putString\("reason", error\.reason\)/,
);
expect(body(kotlin, 'reject')).toContain('errorDetails(error)');
expect(body(kotlin, 'configure')).toContain('errorDetails(error)');
});

it('sets the wrapper platform before configure', () => {
const configure = body(kotlin, 'configure');
const header = configure.indexOf(
'LinkTrailWrapper.setPlatform("react-native", BuildConfig.LINKTRAIL_RN_VERSION)',
);
expect(header).toBeGreaterThanOrEqual(0);
expect(header).toBeLessThan(configure.indexOf('LinkTrail.configure('));
});

it('pins io.linktrail:sdk:0.2.0 exactly', () => {
expect(read('android/build.gradle')).toMatch(
/implementation "io\.linktrail:sdk:0\.2\.0"/,
);
});
});

describe('iOS bridge', () => {
it('maps .invalidEvent to invalidEvent', () => {
expect(body(swift, 'errorCode')).toMatch(
/case \.invalidEvent: return "invalidEvent"/,
);
});

it('passes reason for .invalidEvent in the error user info (reject + onError)', () => {
expect(body(swift, 'errorUserInfo')).toMatch(
/case let \.invalidEvent\(reason\)\?:\s*return \["reason": reason\]/,
);
expect(body(swift, 'errorPayload')).toContain('errorUserInfo(error)');
});

it('calls setSDKIdentifier(platform: "react-native") before configure', () => {
const configure = body(swift, 'configure');
const header = configure.indexOf(
'LinkTrailSDK.LinkTrail.setSDKIdentifier(platform: "react-native", version: Self.wrapperVersion)',
);
expect(header).toBeGreaterThanOrEqual(0);
expect(header).toBeLessThan(
configure.indexOf('LinkTrailSDK.LinkTrail.configure('),
);
});

it('sends the package.json version in the header', () => {
expect(swift).toContain(`static let wrapperVersion = "${pkg.version}"`);
});

it('pins LinkTrailSDK ~> 0.2.0', () => {
expect(read('LinktrailReactNative.podspec')).toMatch(
/s\.dependency "LinkTrailSDK", "~> 0\.2\.0"/,
);
});
});

describe('legacyCode removal', () => {
it.each(['src/errors.ts', 'src/index.ts', 'src/types.ts', 'README.md'])(
'%s no longer mentions legacyCode',
(path) => {
expect(read(path)).not.toMatch(/legacyCode|LinkTrailLegacyErrorCode/);
},
);
});
105 changes: 77 additions & 28 deletions __tests__/parity.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-env jest */
// wrapper-parity 0.1.1: link/attribution buffering, error codes, version.
// Wrapper parity: link/attribution buffering, error codes (incl. invalidEvent), version.
import { Linking } from 'react-native';

type Listener = (payload: unknown) => void;
Expand Down Expand Up @@ -193,7 +193,7 @@ describe('onAttribution replay', () => {
});

describe('error codes', () => {
it('rejects with a LinkTrailError: camelCase code, legacyCode, native message', async () => {
it('rejects with a LinkTrailError: camelCase code, native message', async () => {
mockNative.trackEvent.mockRejectedValue(
Object.assign(new Error('Server returned status 500: boom'), {
code: 'server',
Expand All @@ -204,46 +204,63 @@ describe('error codes', () => {
expect(err).toBeInstanceOf(api.LinkTrailError);
expect(err).toMatchObject({
code: 'server',
legacyCode: 'server',
message: 'Server returned status 500: boom',
statusCode: 500,
body: 'boom',
});
});

it.each([
['missingApiKey', 'missing_api_key'],
['invalidApiKey', 'invalid_api_key'],
['notConfigured', 'not_configured'],
['invalidUrl', 'invalid_url'],
['notALinkTrailUrl', 'not_a_linktrail_url'],
['transport', 'transport'],
['decoding', 'decoding'],
['emptyResponse', 'empty_response'],
['invalidArgument', 'invalid_argument'],
])(
'maps %s <-> legacy %s (either form from native)',
async (code, legacy) => {
for (const nativeCode of [code, legacy]) {
mockNative.trackInstall.mockRejectedValueOnce(
Object.assign(new Error('m'), { code: nativeCode }),
);
await expect(api.LinkTrail.trackInstall()).rejects.toMatchObject({
code,
legacyCode: legacy,
});
}
'missingApiKey',
'invalidApiKey',
'notConfigured',
'invalidUrl',
'notALinkTrailUrl',
'transport',
'decoding',
'emptyResponse',
'invalidArgument',
'invalidEvent',
])('passes the native code %s through', async (code) => {
mockNative.trackInstall.mockRejectedValueOnce(
Object.assign(new Error('m'), { code }),
);
await expect(api.LinkTrail.trackInstall()).rejects.toMatchObject({ code });
});

it('has no legacyCode (removed in 0.2.0)', async () => {
mockNative.trackInstall.mockRejectedValueOnce(
Object.assign(new Error('m'), { code: 'transport' }),
);
const err = await api.LinkTrail.trackInstall().catch((e) => e);
expect(err).not.toHaveProperty('legacyCode');
const listener = jest.fn();
api.LinkTrail.onError(listener);
nativeEmit('onError', { code: 'transport', message: 'offline' });
expect(listener.mock.calls[0][0]).not.toHaveProperty('legacyCode');
});

it.each(['missing_api_key', 'invalid_event', 'E_WHAT'])(
'maps the unrecognised code %s to unknown',
async (nativeCode) => {
mockNative.trackInstall.mockRejectedValueOnce(
Object.assign(new Error('m'), { code: nativeCode }),
);
await expect(api.LinkTrail.trackInstall()).rejects.toMatchObject({
code: 'unknown',
});
},
);

it('maps unrecognised codes to unknown and omits statusCode/body', async () => {
it('maps unrecognised codes to unknown and omits statusCode/body/reason', async () => {
mockNative.handleDeepLink.mockRejectedValue(
Object.assign(new Error('weird'), { code: 'E_WHAT' }),
);
const err = await api.LinkTrail.handleDeepLink('https://x').catch((e) => e);
expect(err.code).toBe('unknown');
expect(err).not.toHaveProperty('statusCode');
expect(err).not.toHaveProperty('body');
expect(err).not.toHaveProperty('reason');
});

it('onError carries statusCode and body for server errors', () => {
Expand All @@ -256,20 +273,52 @@ describe('error codes', () => {
});
expect(listener).toHaveBeenCalledWith({
code: 'server',
legacyCode: 'server',
message: 'Server returned status 503',
statusCode: 503,
});
});
});

describe('invalidEvent (wrapper parity 0.2.0)', () => {
const message = 'Invalid event: value must not be negative (got -1.0)';
const reason = 'value must not be negative (got -1.0)';

it('rejects trackEvent with code invalidEvent, the native message and reason', async () => {
mockNative.trackEvent.mockRejectedValue(
Object.assign(new Error(message), {
code: 'invalidEvent',
userInfo: { reason },
}),
);
const err = await api.LinkTrail.trackEvent('purchase', { value: -1 }).catch(
(e) => e,
);
expect(err).toBeInstanceOf(api.LinkTrailError);
expect(err).toMatchObject({ code: 'invalidEvent', message, reason });
expect(err).not.toHaveProperty('statusCode');
});

it('passes the arguments to native unchanged (no wrapper-side validation)', async () => {
mockNative.trackEvent.mockResolvedValue({ attributed: false });
await api.LinkTrail.trackEvent(' ', { value: NaN, currency: 'usdollar' });
expect(mockNative.trackEvent).toHaveBeenCalledWith(' ', NaN, 'usdollar');
});

it('onError carries reason for invalidEvent', () => {
const listener = jest.fn();
api.LinkTrail.onError(listener);
nativeEmit('onError', { code: 'invalidEvent', message, reason });
expect(listener).toHaveBeenCalledWith({ code: 'invalidEvent', message, reason });
});
});

describe('version', () => {
it('LinkTrail.version equals package.json', () => {
expect(api.LinkTrail.version).toBe(require('../package.json').version);
});

it('nativeSdkVersion comes from native', () => {
mockNative.nativeSdkVersion.mockReturnValue('0.1.0');
expect(api.LinkTrail.nativeSdkVersion).toBe('0.1.0');
mockNative.nativeSdkVersion.mockReturnValue('0.2.0');
expect(api.LinkTrail.nativeSdkVersion).toBe('0.2.0');
});
});
2 changes: 1 addition & 1 deletion android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,6 @@ repositories {

dependencies {
implementation "com.facebook.react:react-android"
implementation "io.linktrail:sdk:0.1.0"
implementation "io.linktrail:sdk:0.2.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0"
}
Loading
Loading