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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Minor version. Read the install change below before upgrading.
- Internal code that was never called: the private deferred deep link handlers in both entry points, the unused `src/utils-interface.ts` (not exported) and a commented-out AppState block.

### Fixed
- Expo: an app without `expo-router` can now bundle `@datalyr/react-native/expo`. The entry's lazy `require('expo-router')` had no try/catch, so Metro could not treat it as optional and stopped with `Unable to resolve module expo-router` (also in 1.8.0). Now only `useDatalyrScreenTracking()` needs expo-router, and without it the hook throws a clear error.
- Events are no longer dead-lettered by a server outage. A 5xx (503 included), 429, 408, a timeout or a network error keeps the event in the queue with the same `eventId`, uses none of its retry budget, and backs the whole queue off (5 s doubling to 5 minutes with 0.5x to 1.0x jitter; never sooner than the server's `Retry-After`, honoured up to 10 minutes, plus 0 to 25% jitter). Before, three failed flushes (about 1 to 2 minutes of 5xx or 429) moved events to the dead-letter store, and a timeout (`Aborted`) was not recognised as a connectivity failure.
- `Retry-After` is now honoured on 5xx answers (ingest answers 503 with `Retry-After` when the fault is its own), not only on 429 and 408. A `Retry-After` longer than 30 s is no longer cut short in-request.
- Any 2xx is a delivered event, whatever its body. Ingest answers 204 with no body for a filtered event; that used to count as a failed send and re-send the event.
Expand Down
13 changes: 11 additions & 2 deletions src/expo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,20 @@ import type { ExpoRouterTrackingConfig as _ExpoRouterConfig } from './expo-route

// Lazy-resolved expo-router hook. Resolved once at first call, not inside the
// hook body, so that hook call count stays stable across renders.
//
// The require must stay inside try/catch: Metro resolves every literal
// require when it bundles, and only treats one inside a try block as optional
// (allowOptionalDependencies, on in Metro's, React Native's and Expo's default
// config). Without it, an app without expo-router cannot bundle this entry.
let _usePathname: (() => string) | null = null;
function getUsePathname(): () => string {
if (!_usePathname) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
_usePathname = (require('expo-router') as { usePathname: () => string }).usePathname;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
_usePathname = (require('expo-router') as { usePathname: () => string }).usePathname;
} catch {
throw new Error('[Datalyr] useDatalyrScreenTracking needs expo-router. Install it, or call datalyr.screen() yourself.');
}
}
return _usePathname;
}
Expand Down
87 changes: 87 additions & 0 deletions tests/expo-router-optional.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// The Expo entry must bundle in an app without expo-router.
//
// Metro resolves every literal require() when it bundles, wherever the call
// is, and treats one as optional only inside a try block
// (allowOptionalDependencies, on in Metro's, React Native's and Expo's default
// config). Metro reads src/expo.ts (the "react-native" export condition), and
// lib/expo.js is the tsc build of it.

import { existsSync, readFileSync } from 'fs';
import { join, resolve } from 'path';
import * as ts from 'typescript';

jest.mock('expo-application', () => ({
nativeApplicationVersion: '1.0.0', nativeBuildVersion: '1',
applicationId: 'com.datalyr.test', getInstallationTimeAsync: async () => new Date(0),
}), { virtual: true });
jest.mock('expo-device', () => ({
modelName: 'Test Device', deviceName: 'Test Device', manufacturer: 'Test',
osVersion: '17.0', isDevice: true,
}), { virtual: true });
jest.mock('expo-network', () => ({
NetworkStateType: { WIFI: 'WIFI' },
getNetworkStateAsync: async () => ({ type: 'WIFI', isConnected: true }),
}), { virtual: true });
// An app without expo-router: requiring it throws, as Metro's optional
// dependency stub does.
jest.mock('expo-router', () => {
throw new Error("Cannot find module 'expo-router'");
}, { virtual: true });

const repoRoot = resolve(__dirname, '..');

// Each require('expo-router') call in the file, and whether it sits inside the
// try block of a try statement.
function expoRouterRequires(file: string): boolean[] {
const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
const found: boolean[] = [];
const visit = (node: ts.Node): void => {
if (
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === 'require' &&
node.arguments.length === 1 &&
ts.isStringLiteral(node.arguments[0]) &&
node.arguments[0].text === 'expo-router'
) {
let inTry = false;
for (let child: ts.Node = node, parent = node.parent; parent; child = parent, parent = parent.parent) {
if (ts.isTryStatement(parent) && parent.tryBlock === child) {
inTry = true;
break;
}
if (ts.isFunctionLike(parent)) {
// A try outside the enclosing function does not guard the call.
if (ts.isTryStatement(parent.parent) && parent.parent.tryBlock === parent) inTry = true;
break;
}
}
found.push(inTry);
}
ts.forEachChild(node, visit);
};
visit(source);
return found;
}

describe('expo-router is optional for the Expo entry', () => {
test('every require of expo-router in src/expo.ts is inside a try block', () => {
const found = expoRouterRequires(join(repoRoot, 'src', 'expo.ts'));
expect(found.length).toBeGreaterThan(0);
expect(found.every(Boolean)).toBe(true);
});

const built = join(repoRoot, 'lib', 'expo.js');
(existsSync(built) ? test : test.skip)('the same holds in the built lib/expo.js', () => {
const found = expoRouterRequires(built);
expect(found.length).toBeGreaterThan(0);
expect(found.every(Boolean)).toBe(true);
});

test('without expo-router the entry loads, and only the hook fails, with a clear message', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const expo = require('../src/expo');
expect(typeof expo.useDatalyrScreenTracking).toBe('function');
expect(() => expo.useDatalyrScreenTracking()).toThrow(/needs expo-router/);
});
});