@metarouter/react-native-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MetaRouter
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,163 @@
1
+ # @metarouter/react-native-sdk
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@metarouter/react-native-sdk)](https://www.npmjs.com/package/@metarouter/react-native-sdk)
4
+ [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
5
+
6
+ A lightweight React Native analytics SDK that transmits events to your MetaRouter cluster using Segment-compatible methods. Built on top of `@segment/analytics-react-native`.
7
+
8
+ ## Installation
9
+
10
+ ```sh
11
+ npm install @metarouter/react-native-sdk
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ### Basic Setup
17
+
18
+ ```js
19
+ import { createMetaRouterClient } from "@metarouter/react-native-sdk";
20
+
21
+ // Initialize the analytics client
22
+ const analytics = createMetaRouterClient({
23
+ writeKey: "your-write-key",
24
+ ingestionEndpoint: "https://your-ingestion-endpoint.com/events",
25
+ debug: true, // Optional: enable debug mode
26
+ flushInterval: 30, // Optional: flush events every 30 seconds
27
+ });
28
+ ```
29
+
30
+ ### React Context Usage
31
+
32
+ ```jsx
33
+ import React from "react";
34
+ import {
35
+ createMetaRouterClient,
36
+ MetaRouterProvider,
37
+ useMetaRouter,
38
+ } from "@metarouter/react-native-sdk";
39
+
40
+ const App = () => {
41
+ const analytics = createMetaRouterClient({
42
+ writeKey: "your-write-key",
43
+ ingestionEndpoint: "https://your-ingestion-endpoint.com/events",
44
+ });
45
+
46
+ return (
47
+ <MetaRouterProvider client={analytics}>
48
+ <YourApp />
49
+ </MetaRouterProvider>
50
+ );
51
+ };
52
+
53
+ // Use analytics in any component
54
+ const MyComponent = () => {
55
+ const analytics = useMetaRouter();
56
+
57
+ const handleButtonPress = () => {
58
+ analytics.track("Button Pressed", {
59
+ buttonName: "submit",
60
+ timestamp: Date.now(),
61
+ });
62
+ };
63
+
64
+ return <Button onPress={handleButtonPress} title="Submit" />;
65
+ };
66
+ ```
67
+
68
+ ### Direct Usage
69
+
70
+ ```js
71
+ import { createMetaRouterClient } from "@metarouter/react-native-sdk";
72
+
73
+ // Initialize
74
+ const analytics = createMetaRouterClient({
75
+ writeKey: "your-write-key",
76
+ ingestionEndpoint: "https://your-ingestion-endpoint.com/events",
77
+ });
78
+
79
+ // Track events
80
+ analytics.track("User Action", {
81
+ action: "button_click",
82
+ screen: "home",
83
+ });
84
+
85
+ // Identify users
86
+ analytics.identify("user123", {
87
+ name: "John Doe",
88
+ email: "john@example.com",
89
+ });
90
+
91
+ // Track screen views
92
+ analytics.screen("Home Screen", {
93
+ category: "navigation",
94
+ });
95
+
96
+ // Group users
97
+ analytics.group("company123", {
98
+ name: "Acme Corp",
99
+ industry: "technology",
100
+ });
101
+
102
+ // Flush events immediately
103
+ analytics.flush();
104
+
105
+ // Cleanup when done
106
+ analytics.cleanup();
107
+ ```
108
+
109
+ ## API Reference
110
+
111
+ ### createMetaRouterClient(options)
112
+
113
+ Creates and initializes the analytics client.
114
+
115
+ **Options:**
116
+
117
+ - `writeKey` (string, required): Your write key
118
+ - `ingestionEndpoint` (string, required): Your custom ingestion endpoint URL
119
+ - `debug` (boolean, optional): Enable debug mode
120
+ - `flushAt` (number, optional): Number of events to batch before sending
121
+ - `flushInterval` (number, optional): Interval in seconds to flush events
122
+ - `trackLifecycleEvents` (boolean, optional): Track app lifecycle events
123
+ - `maxBatchSize` (number, optional): Maximum batch size for events
124
+
125
+ ### Analytics Interface
126
+
127
+ The analytics client provides the following methods:
128
+
129
+ - `track(event: string, properties?: Record<string, any>)`: Track custom events
130
+ - `identify(userId: string, traits?: Record<string, any>)`: Identify users
131
+ - `group(groupId: string, traits?: Record<string, any>)`: Group users
132
+ - `screen(name: string, properties?: Record<string, any>)`: Track screen views
133
+ - `alias(newUserId: string)`: Alias user IDs
134
+ - `flush()`: Flush events immediately
135
+ - `cleanup()`: Clean up resources
136
+
137
+ ### React Hooks
138
+
139
+ - `useMetaRouter()`: Hook to access the analytics client within a `MetaRouterProvider`
140
+
141
+ ### Components
142
+
143
+ - `MetaRouterProvider`: React context provider for analytics client
144
+
145
+ ## Features
146
+
147
+ - 🎯 **Custom Endpoints**: Send events to your own ingestion endpoints
148
+ - 📱 **React Native Optimized**: Built on top of Segment's analytics-react-native
149
+ - 🎣 **React Hooks**: Easy integration with React components
150
+ - 🔧 **TypeScript Support**: Full TypeScript support included
151
+ - 🚀 **Lightweight**: Minimal overhead and dependencies
152
+
153
+ ## License
154
+
155
+ MIT
156
+
157
+ ---
158
+
159
+ ## Attributions
160
+
161
+ This library includes code from the following third-party packages:
162
+
163
+ - [@segment/analytics-react-native](https://github.com/segmentio/analytics-react-native), MIT License
@@ -0,0 +1,25 @@
1
+ export interface InitOptions {
2
+ writeKey: string;
3
+ ingestionEndpoint: string;
4
+ debug?: boolean;
5
+ flushAt?: number;
6
+ flushInterval?: number;
7
+ trackLifecycleEvents?: boolean;
8
+ maxBatchSize?: number;
9
+ }
10
+ export type AnalyticsInterface = {
11
+ track: (event: string, props?: Record<string, any>) => void;
12
+ identify: (userId: string, traits?: Record<string, any>) => void;
13
+ group: (groupId: string, traits?: Record<string, any>) => void;
14
+ screen: (name: string, props?: Record<string, any>) => void;
15
+ alias: (newUserId: string) => void;
16
+ flush: () => void;
17
+ cleanup: () => void;
18
+ };
19
+ export declare const MetaRouter: {
20
+ init: (options: InitOptions) => Promise<AnalyticsInterface>;
21
+ getClient(): AnalyticsInterface;
22
+ create(opts: InitOptions): AnalyticsInterface;
23
+ reset: () => Promise<void>;
24
+ };
25
+ //# sourceMappingURL=MetaRouter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MetaRouter.d.ts","sourceRoot":"","sources":["../src/MetaRouter.ts"],"names":[],"mappings":"AASA,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;IAC5D,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;IACjE,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;IAC/D,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;IAC5D,KAAK,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAEF,eAAO,MAAM,UAAU;oBACC,WAAW,KAAG,OAAO,CAAC,kBAAkB,CAAC;iBAqClD,kBAAkB;iBAIlB,WAAW,GAAG,kBAAkB;;CAW9C,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { createClient } from '@segment/analytics-react-native';
2
+ import { MetaRouterPlugin } from './MetaRouterPlugin';
3
+ import { proxyClient, setRealClient } from './proxyClient';
4
+ let analytics = null;
5
+ let analyticsInterface = null;
6
+ let initialized = false;
7
+ export const MetaRouter = {
8
+ init: async (options) => {
9
+ var _a;
10
+ if (initialized)
11
+ return analyticsInterface;
12
+ if (!options.writeKey)
13
+ throw new Error('writeKey is required');
14
+ if (!options.ingestionEndpoint)
15
+ throw new Error('ingestionEndpoint is required');
16
+ const config = {
17
+ writeKey: options.writeKey,
18
+ debug: options.debug,
19
+ flushInterval: options.flushInterval,
20
+ useSegmentEndpoints: false,
21
+ trackAppLifecycleEvents: (_a = options.trackLifecycleEvents) !== null && _a !== void 0 ? _a : true,
22
+ autoAddSegmentDestination: false,
23
+ };
24
+ analytics = createClient(config);
25
+ analytics.add({ plugin: new MetaRouterPlugin(options.ingestionEndpoint, options.writeKey) });
26
+ await analytics.init();
27
+ analyticsInterface = {
28
+ track: (event, props) => analytics.track(event, props),
29
+ identify: (userId, traits) => analytics.identify(userId, traits),
30
+ group: (groupId, traits) => analytics.group(groupId, traits),
31
+ screen: (name, props) => analytics.screen(name, props),
32
+ alias: (newUserId) => analytics.alias(newUserId),
33
+ flush: () => analytics.flush(),
34
+ cleanup: () => analytics.cleanup(),
35
+ };
36
+ initialized = true;
37
+ // Hand off to proxy
38
+ setRealClient(analyticsInterface);
39
+ return analyticsInterface;
40
+ },
41
+ getClient() {
42
+ return initialized ? analyticsInterface : proxyClient;
43
+ },
44
+ create(opts) {
45
+ void this.init(opts).catch(console.error);
46
+ return this.getClient();
47
+ },
48
+ reset: async () => {
49
+ await (analytics === null || analytics === void 0 ? void 0 : analytics.cleanup());
50
+ analytics = null;
51
+ analyticsInterface = null;
52
+ initialized = false;
53
+ },
54
+ };
@@ -0,0 +1,10 @@
1
+ import { DestinationPlugin, PluginType, SegmentEvent } from '@segment/analytics-react-native';
2
+ export declare class MetaRouterPlugin extends DestinationPlugin {
3
+ private ingestionEndpoint;
4
+ private writeKey;
5
+ key: string;
6
+ type: PluginType;
7
+ constructor(ingestionEndpoint: string, writeKey: string);
8
+ execute(event: SegmentEvent): Promise<SegmentEvent>;
9
+ }
10
+ //# sourceMappingURL=MetaRouterPlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MetaRouterPlugin.d.ts","sourceRoot":"","sources":["../src/MetaRouterPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qBAAa,gBAAiB,SAAQ,iBAAiB;IAKzC,OAAO,CAAC,iBAAiB;IAAU,OAAO,CAAC,QAAQ;IAH/D,GAAG,SAA2B;IAC9B,IAAI,aAAyB;gBAET,iBAAiB,EAAE,MAAM,EAAU,QAAQ,EAAE,MAAM;IAIjE,OAAO,CAAC,KAAK,EAAE,YAAY;CAclC"}
@@ -0,0 +1,23 @@
1
+ import { DestinationPlugin, PluginType } from '@segment/analytics-react-native';
2
+ export class MetaRouterPlugin extends DestinationPlugin {
3
+ constructor(ingestionEndpoint, writeKey) {
4
+ super();
5
+ this.ingestionEndpoint = ingestionEndpoint;
6
+ this.writeKey = writeKey;
7
+ // Required by Segment
8
+ this.key = 'MetaRouterDestination';
9
+ this.type = PluginType.destination;
10
+ }
11
+ async execute(event) {
12
+ const enrichedEvent = {
13
+ ...event,
14
+ writeKey: this.writeKey,
15
+ };
16
+ await fetch(this.ingestionEndpoint, {
17
+ method: 'POST',
18
+ headers: { 'Content-Type': 'application/json' },
19
+ body: JSON.stringify(enrichedEvent),
20
+ });
21
+ return event;
22
+ }
23
+ }
@@ -0,0 +1,8 @@
1
+ import React from "react";
2
+ import type { AnalyticsInterface } from "./MetaRouter";
3
+ export declare const MetaRouterProvider: React.FC<{
4
+ client: AnalyticsInterface;
5
+ children: React.ReactNode;
6
+ }>;
7
+ export declare const useMetaRouter: () => AnalyticsInterface;
8
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAoC,MAAM,OAAO,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAIvD,eAAO,MAAM,kBAAkB,EAAE,KAAK,CAAC,EAAE,CAAC;IACxC,MAAM,EAAE,kBAAkB,CAAC;IAC3B,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B,CAIA,CAAC;AAEF,eAAO,MAAM,aAAa,QAAO,kBAKhC,CAAC"}
package/lib/context.js ADDED
@@ -0,0 +1,9 @@
1
+ import React, { createContext, useContext } from "react";
2
+ const AnalyticsContext = createContext(null);
3
+ export const MetaRouterProvider = ({ client, children }) => (React.createElement(AnalyticsContext.Provider, { value: client }, children));
4
+ export const useMetaRouter = () => {
5
+ const ctx = useContext(AnalyticsContext);
6
+ if (!ctx)
7
+ throw new Error("useMetaRouter must be used inside a <MetaRouterProvider>");
8
+ return ctx;
9
+ };
@@ -0,0 +1,3 @@
1
+ import type { AnalyticsInterface, InitOptions } from './MetaRouter';
2
+ export declare const createMetaRouterClient: (options: InitOptions) => AnalyticsInterface;
3
+ //# sourceMappingURL=createMetaRouterClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createMetaRouterClient.d.ts","sourceRoot":"","sources":["../src/createMetaRouterClient.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEpE,eAAO,MAAM,sBAAsB,GACjC,SAAS,WAAW,KACnB,kBAMF,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { MetaRouter } from './MetaRouter';
2
+ export const createMetaRouterClient = (options) => {
3
+ void MetaRouter.init(options).catch((err) => {
4
+ console.error('[MetaRouter] init failed:', err);
5
+ });
6
+ return MetaRouter.getClient();
7
+ };
package/lib/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { createMetaRouterClient } from "./createMetaRouterClient";
2
+ export { MetaRouterProvider, useMetaRouter } from "./context";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createMetaRouterClient } from "./createMetaRouterClient";
2
+ export { MetaRouterProvider, useMetaRouter } from "./context";
@@ -0,0 +1,4 @@
1
+ import type { AnalyticsInterface } from './MetaRouter';
2
+ export declare const proxyClient: AnalyticsInterface;
3
+ export declare function setRealClient(c: AnalyticsInterface): void;
4
+ //# sourceMappingURL=proxyClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"proxyClient.d.ts","sourceRoot":"","sources":["../src/proxyClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAIvD,eAAO,MAAM,WAAW,EAAE,kBAsBzB,CAAC;AAIF,wBAAgB,aAAa,CAAC,CAAC,EAAE,kBAAkB,QAMlD"}
@@ -0,0 +1,31 @@
1
+ const pendingCalls = [];
2
+ export const proxyClient = {
3
+ track: (event, props) => {
4
+ pendingCalls.push(() => client.track(event, props));
5
+ },
6
+ identify: (userId, traits) => {
7
+ pendingCalls.push(() => client.identify(userId, traits));
8
+ },
9
+ group: (groupId, traits) => {
10
+ pendingCalls.push(() => client.group(groupId, traits));
11
+ },
12
+ screen: (name, props) => {
13
+ pendingCalls.push(() => client.screen(name, props));
14
+ },
15
+ alias: (newUserId) => {
16
+ pendingCalls.push(() => client.alias(newUserId));
17
+ },
18
+ flush: () => {
19
+ pendingCalls.push(() => client.flush());
20
+ },
21
+ cleanup: () => {
22
+ pendingCalls.push(() => client.cleanup());
23
+ },
24
+ };
25
+ let client = null;
26
+ export function setRealClient(c) {
27
+ client = c;
28
+ // Flush pending
29
+ pendingCalls.forEach((fn) => fn());
30
+ pendingCalls.length = 0;
31
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@metarouter/react-native-sdk",
3
+ "version": "0.1.0",
4
+ "main": "./lib/index.js",
5
+ "types": "./lib/index.d.ts",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./lib/index.js",
9
+ "require": "./lib/index.js",
10
+ "types": "./lib/index.d.ts"
11
+ }
12
+ },
13
+ "files": [
14
+ "lib",
15
+ "react-native.config.js"
16
+ ],
17
+ "scripts": {
18
+ "clean": "rm -rf lib",
19
+ "build": "tsc --project tsconfig.build.json",
20
+ "prepare": "npm run build",
21
+ "test": "jest"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "keywords": [
27
+ "react-native",
28
+ "sdk",
29
+ "metarouter"
30
+ ],
31
+ "author": "Christopher Houdlette",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/choudlet/react-native-sdk"
36
+ },
37
+ "dependencies": {
38
+ "@segment/analytics-react-native": "^2.21.2",
39
+ "@segment/sovran-react-native": "^1.1.3",
40
+ "react-native-get-random-values": "^1.11.0"
41
+ },
42
+ "peerDependencies": {
43
+ "react": "*",
44
+ "react-native": "*"
45
+ },
46
+ "devDependencies": {
47
+ "@types/react": "^19.1.8",
48
+ "jest": "^30.0.4",
49
+ "metro-react-native-babel-preset": "^0.77.0",
50
+ "typescript": "^5.8.3"
51
+ },
52
+ "react-native": "./lib/index.js"
53
+ }
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ dependencies: {
3
+ '@segment/analytics-react-native': {},
4
+ '@segment/sovran-react-native': {},
5
+ 'react-native-get-random-values': {},
6
+ },
7
+ };