@appolabs/sdk 1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Appo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,439 @@
1
+ # @appolabs/sdk
2
+
3
+ JavaScript bridge SDK for accessing native device features from web apps running inside React Native WebViews.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @appolabs/sdk
9
+ ```
10
+
11
+ ```bash
12
+ pnpm add @appolabs/sdk
13
+ ```
14
+
15
+ ```bash
16
+ yarn add @appolabs/sdk
17
+ ```
18
+
19
+ Or include via script tag (auto-initializes `window.appo`):
20
+
21
+ ```html
22
+ <script src="https://unpkg.com/@appolabs/sdk"></script>
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```typescript
28
+ import { getAppo } from '@appolabs/sdk';
29
+
30
+ const appo = getAppo();
31
+
32
+ if (appo.isNative) {
33
+ const status = await appo.push.requestPermission();
34
+ if (status === 'granted') {
35
+ const token = await appo.push.getToken();
36
+ }
37
+ }
38
+ ```
39
+
40
+ ## Initialization
41
+
42
+ The SDK provides two initialization functions and a singleton pattern:
43
+
44
+ ```typescript
45
+ import { getAppo, initAppo } from '@appolabs/sdk';
46
+
47
+ // Option 1: getAppo() - initializes on first call, returns existing instance after
48
+ const appo = getAppo();
49
+
50
+ // Option 2: initAppo() - explicit initialization, attaches to window.appo
51
+ const appo = initAppo();
52
+ ```
53
+
54
+ When loaded via `<script>` tag, the SDK auto-initializes and attaches to `window.appo`. Subsequent calls to `getAppo()` or `initAppo()` return the same singleton instance.
55
+
56
+ The `isNative` property indicates whether the SDK is running inside a native Appo container (`true`) or a regular browser (`false`).
57
+
58
+ ```typescript
59
+ const appo = getAppo();
60
+ console.log(appo.isNative); // true inside Appo app, false in browser
61
+ console.log(appo.version); // SDK version string
62
+ ```
63
+
64
+ ## API Reference
65
+
66
+ ### Push Notifications
67
+
68
+ ```typescript
69
+ interface PushApi {
70
+ requestPermission(): Promise<PermissionStatus>;
71
+ getToken(): Promise<string | null>;
72
+ onMessage(callback: (message: PushMessage) => void): () => void;
73
+ onResponse(callback: (response: PushResponse) => void): () => void;
74
+ }
75
+ ```
76
+
77
+ Request permission and retrieve the push token:
78
+
79
+ ```typescript
80
+ const status = await appo.push.requestPermission();
81
+ // status: 'granted' | 'denied' | 'undetermined'
82
+
83
+ if (status === 'granted') {
84
+ const token = await appo.push.getToken();
85
+ // token: string | null
86
+ }
87
+ ```
88
+
89
+ Subscribe to incoming push notifications:
90
+
91
+ ```typescript
92
+ const unsubscribe = appo.push.onMessage((message) => {
93
+ console.log(message.title, message.body, message.data);
94
+ });
95
+
96
+ // Later: stop listening
97
+ unsubscribe();
98
+ ```
99
+
100
+ Subscribe to notification tap events (when user taps a notification):
101
+
102
+ ```typescript
103
+ const unsubscribe = appo.push.onResponse((response) => {
104
+ console.log(response.title, response.body, response.actionIdentifier);
105
+ });
106
+ ```
107
+
108
+ ### Biometrics
109
+
110
+ ```typescript
111
+ interface BiometricsApi {
112
+ isAvailable(): Promise<boolean>;
113
+ authenticate(reason: string): Promise<boolean>;
114
+ }
115
+ ```
116
+
117
+ ```typescript
118
+ const available = await appo.biometrics.isAvailable();
119
+ if (available) {
120
+ const success = await appo.biometrics.authenticate('Confirm your identity');
121
+ }
122
+ ```
123
+
124
+ ### Camera
125
+
126
+ ```typescript
127
+ interface CameraApi {
128
+ requestPermission(): Promise<PermissionStatus>;
129
+ takePicture(): Promise<CameraResult>;
130
+ }
131
+ ```
132
+
133
+ ```typescript
134
+ const status = await appo.camera.requestPermission();
135
+ if (status === 'granted') {
136
+ const result = await appo.camera.takePicture();
137
+ // result: { uri: string, base64?: string, width: number, height: number }
138
+ }
139
+ ```
140
+
141
+ ### Location
142
+
143
+ ```typescript
144
+ interface LocationApi {
145
+ requestPermission(): Promise<PermissionStatus>;
146
+ getCurrentPosition(): Promise<Position>;
147
+ }
148
+ ```
149
+
150
+ ```typescript
151
+ const status = await appo.location.requestPermission();
152
+ if (status === 'granted') {
153
+ const position = await appo.location.getCurrentPosition();
154
+ // position: { latitude, longitude, altitude?, accuracy?, timestamp }
155
+ }
156
+ ```
157
+
158
+ ### Haptics
159
+
160
+ ```typescript
161
+ interface HapticsApi {
162
+ impact(style: HapticImpactStyle): void;
163
+ notification(type: HapticNotificationType): void;
164
+ }
165
+ ```
166
+
167
+ ```typescript
168
+ appo.haptics.impact('light'); // 'light' | 'medium' | 'heavy'
169
+ appo.haptics.notification('success'); // 'success' | 'warning' | 'error'
170
+ ```
171
+
172
+ ### Storage
173
+
174
+ ```typescript
175
+ interface StorageApi {
176
+ get(key: string): Promise<string | null>;
177
+ set(key: string, value: string): Promise<void>;
178
+ delete(key: string): Promise<void>;
179
+ }
180
+ ```
181
+
182
+ ```typescript
183
+ await appo.storage.set('auth_token', 'abc123');
184
+ const token = await appo.storage.get('auth_token');
185
+ await appo.storage.delete('auth_token');
186
+ ```
187
+
188
+ ### Share
189
+
190
+ ```typescript
191
+ interface ShareApi {
192
+ open(options: ShareOptions): Promise<ShareResult>;
193
+ }
194
+ ```
195
+
196
+ ```typescript
197
+ const result = await appo.share.open({
198
+ title: 'Check this out',
199
+ message: 'Content to share',
200
+ url: 'https://example.com',
201
+ });
202
+ // result: { success: boolean, action?: string }
203
+ ```
204
+
205
+ ### Network
206
+
207
+ ```typescript
208
+ interface NetworkApi {
209
+ getStatus(): Promise<NetworkStatus>;
210
+ onChange(callback: (status: NetworkStatus) => void): () => void;
211
+ }
212
+ ```
213
+
214
+ ```typescript
215
+ const status = await appo.network.getStatus();
216
+ // status: { isConnected: boolean, type: 'wifi' | 'cellular' | 'none' | 'unknown' }
217
+
218
+ const unsubscribe = appo.network.onChange((status) => {
219
+ console.log('Network changed:', status.isConnected, status.type);
220
+ });
221
+ ```
222
+
223
+ ### Device
224
+
225
+ ```typescript
226
+ interface DeviceApi {
227
+ getInfo(): Promise<DeviceInfo>;
228
+ }
229
+ ```
230
+
231
+ ```typescript
232
+ const info = await appo.device.getInfo();
233
+ // info: { platform, osVersion, appVersion, deviceId, deviceName, isTablet }
234
+ ```
235
+
236
+ ## Error Handling
237
+
238
+ All bridge operations that require a native environment throw `AppoError` with categorized error codes:
239
+
240
+ ```typescript
241
+ import { AppoError, AppoErrorCode } from '@appolabs/sdk';
242
+
243
+ try {
244
+ const token = await appo.push.getToken();
245
+ } catch (error) {
246
+ if (error instanceof AppoError) {
247
+ switch (error.code) {
248
+ case AppoErrorCode.NOT_NATIVE:
249
+ // Not running inside a native Appo app
250
+ break;
251
+ case AppoErrorCode.TIMEOUT:
252
+ // Native layer did not respond within 30s
253
+ break;
254
+ case AppoErrorCode.NATIVE_ERROR:
255
+ // Native handler returned an error
256
+ break;
257
+ case AppoErrorCode.BRIDGE_UNAVAILABLE:
258
+ // Bridge communication channel unavailable
259
+ break;
260
+ }
261
+ console.log(error.message, error.detail);
262
+ }
263
+ }
264
+ ```
265
+
266
+ `AppoError` extends `Error`, so existing `catch` blocks continue to work without modification.
267
+
268
+ ```typescript
269
+ class AppoError extends Error {
270
+ readonly code: AppoErrorCode;
271
+ readonly detail?: string;
272
+ }
273
+
274
+ enum AppoErrorCode {
275
+ NOT_NATIVE = 'NOT_NATIVE',
276
+ TIMEOUT = 'TIMEOUT',
277
+ NATIVE_ERROR = 'NATIVE_ERROR',
278
+ BRIDGE_UNAVAILABLE = 'BRIDGE_UNAVAILABLE',
279
+ }
280
+ ```
281
+
282
+ ## Logging
283
+
284
+ The SDK produces no console output by default. Use `setLogger` to observe bridge activity:
285
+
286
+ ```typescript
287
+ import { setLogger } from '@appolabs/sdk';
288
+
289
+ setLogger((level, message, data) => {
290
+ // level: 'debug' | 'warn' | 'error'
291
+ console.log(`[appo:${level}]`, message, data);
292
+ });
293
+
294
+ // Disable logging
295
+ setLogger(null);
296
+ ```
297
+
298
+ Log events include message sends, responses received, timeouts, and parse failures. Payloads are excluded from log data to prevent leaking sensitive information.
299
+
300
+ ## Browser Fallbacks
301
+
302
+ All APIs provide fallback behavior when running outside a native Appo container:
303
+
304
+ | Feature | Method | Fallback |
305
+ |---------|--------|----------|
306
+ | Push | `requestPermission()` | Returns `'denied'` |
307
+ | Push | `getToken()` | Returns `null` |
308
+ | Push | `onMessage()` | Returns no-op unsubscribe |
309
+ | Push | `onResponse()` | Returns no-op unsubscribe |
310
+ | Biometrics | `isAvailable()` | Returns `false` |
311
+ | Biometrics | `authenticate()` | Returns `false` |
312
+ | Camera | `requestPermission()` | Returns `'denied'` |
313
+ | Camera | `takePicture()` | Throws `Error` |
314
+ | Location | `requestPermission()` | Returns `'denied'` |
315
+ | Location | `getCurrentPosition()` | Throws `Error` |
316
+ | Haptics | `impact()` | No-op |
317
+ | Haptics | `notification()` | No-op |
318
+ | Storage | `get()` / `set()` / `delete()` | Uses `localStorage` |
319
+ | Share | `open()` | Uses `navigator.share` if available, otherwise `{ success: false }` |
320
+ | Network | `getStatus()` | Returns `{ isConnected: navigator.onLine, type: 'unknown' }` |
321
+ | Network | `onChange()` | Listens to browser `online`/`offline` events |
322
+ | Device | `getInfo()` | Returns user agent-based info with `osVersion: 'web'` |
323
+
324
+ ## TypeScript
325
+
326
+ All types are exported for use in consuming applications:
327
+
328
+ ```typescript
329
+ import type {
330
+ // Core
331
+ Appo,
332
+ PermissionStatus,
333
+
334
+ // Push
335
+ PushApi,
336
+ PushMessage,
337
+ PushResponse,
338
+
339
+ // Camera
340
+ CameraApi,
341
+ CameraResult,
342
+
343
+ // Location
344
+ LocationApi,
345
+ Position,
346
+
347
+ // Haptics
348
+ HapticsApi,
349
+ HapticImpactStyle,
350
+ HapticNotificationType,
351
+
352
+ // Storage
353
+ StorageApi,
354
+
355
+ // Share
356
+ ShareApi,
357
+ ShareOptions,
358
+ ShareResult,
359
+
360
+ // Network
361
+ NetworkApi,
362
+ NetworkStatus,
363
+
364
+ // Device
365
+ DeviceApi,
366
+ DeviceInfo,
367
+
368
+ // Biometrics
369
+ BiometricsApi,
370
+
371
+ // Bridge internals
372
+ BridgeResponse,
373
+ BridgeEvent,
374
+
375
+ // Logging
376
+ AppoLogLevel,
377
+ AppoLogger,
378
+ } from '@appolabs/sdk';
379
+
380
+ // Value exports
381
+ import {
382
+ getAppo,
383
+ initAppo,
384
+ setLogger,
385
+ AppoError,
386
+ AppoErrorCode,
387
+ isBridgeResponse,
388
+ isBridgeEvent,
389
+ VERSION,
390
+ } from '@appolabs/sdk';
391
+ ```
392
+
393
+ ## Architecture
394
+
395
+ The SDK communicates with the native React Native layer through `window.ReactNativeWebView.postMessage()`:
396
+
397
+ ```
398
+ Web App (SDK) React Native App
399
+ ───────────────── ─────────────────
400
+ sendMessage(type, payload)
401
+ │
402
+ ├─ Generate unique ID
403
+ ├─ Register pending callback
404
+ ├─ postMessage({ id, type, payload })
405
+ │ onMessage(event)
406
+ │ ├─ Parse message
407
+ │ ├─ Dispatch to handler
408
+ │ └─ Send response ──────┐
409
+ │ │
410
+ ◄──────────────────── { id, success, data } ──────────────────┘
411
+ │
412
+ ├─ Match response to pending request by ID
413
+ ├─ Resolve/reject promise
414
+ └─ Return data to caller
415
+ ```
416
+
417
+ Event broadcasts flow from native to web:
418
+
419
+ ```
420
+ React Native App Web App (SDK)
421
+ ───────────────── ─────────────────
422
+ Native event fires
423
+ │
424
+ ├─ broadcastEvent({ event, data })
425
+ │ handleNativeMessage()
426
+ │ ├─ Detect event (no id field)
427
+ │ └─ Notify registered listeners
428
+ │
429
+ └─ Example events:
430
+ 'push.message' → push.onMessage() callbacks
431
+ 'push.response' → push.onResponse() callbacks
432
+ 'network.change' → network.onChange() callbacks
433
+ ```
434
+
435
+ All `sendMessage` calls have a default 30-second timeout. Message IDs use the format `msg_{timestamp}_{counter}` for correlation.
436
+
437
+ ## License
438
+
439
+ MIT