@livx.cc/native-kit 0.16.1 → 0.18.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/README.md CHANGED
@@ -13,6 +13,17 @@ await kit.haptics.impact('medium'); // native vibration in the shell, no-op/
13
13
  const photo = await kit.photos.pick(); // native picker on device, <input type=file> on web
14
14
  ```
15
15
 
16
+ ### Analytics context
17
+
18
+ `kit.context()` returns one flat, vendor-neutral property bag (client taxonomy, app version/build, install source, device, push permission, …) — spread it straight into your analytics super-properties. Native-only fields degrade gracefully on web. First-party & non-tracking: the install id is iOS IDFV / an Android UUID, never IDFA/GAID.
19
+
20
+ ```ts
21
+ import { kit } from '@livx.cc/native-kit';
22
+ mixpanel.register(await kit.context());
23
+ // → { client: 'native-ios', platform: 'ios', app_version: '1.0.3',
24
+ // install_source: 'testflight', device_model: 'iPhone15,3', push_permission: 'granted', … }
25
+ ```
26
+
16
27
  The kit detects whether it's running inside the appwrap shell and routes each call to the native bridge or a web fallback, so a single web build works everywhere. Capabilities advertise their real backing (`native` / `web` / `none`) so your UI can be honest about what's available.
17
28
 
18
29
  Covers haptics, share, storage, notifications, OAuth, billing (IAP), health, geo, camera, photos, contacts, calendar, motion, reviews, and more.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livx.cc/native-kit",
3
- "version": "0.16.1",
3
+ "version": "0.18.0",
4
4
  "description": "Isomorphic native-capabilities kit for PWAs — same API in browser and in an appwrap native shell. Zero dependencies.",
5
5
  "license": "MIT",
6
6
  "author": "Elya Livshitz",
@@ -26,6 +26,7 @@ import { ShareModule } from '../modules/share';
26
26
  import { StorageModule } from '../modules/storage';
27
27
  import { ToastModule } from '../modules/toast';
28
28
  import { UiModule } from '../modules/ui';
29
+ import { UpdatesModule } from '../modules/updates';
29
30
 
30
31
  export class NativeKitOptions {
31
32
  /** Priority order; first adapter whose detect() passes wins. */
@@ -33,6 +34,38 @@ export class NativeKitOptions {
33
34
  handshakeTimeoutMs = 3000;
34
35
  }
35
36
 
37
+ /**
38
+ * Flat, vendor-neutral analytics bag — spread straight into your analytics provider's
39
+ * super-properties (e.g. `mixpanel.register(await kit.context())`). Native-only fields
40
+ * degrade gracefully (omitted/undefined) on web and on older shells. snake_case keys
41
+ * match common analytics conventions.
42
+ */
43
+ export interface KitContext {
44
+ /** Coarse runtime taxonomy: 'native-ios' | 'native-android' | 'web'. */
45
+ client: string;
46
+ is_native: boolean;
47
+ platform: Platform;
48
+ app_id?: string;
49
+ app_name?: string;
50
+ app_version?: string;
51
+ app_build?: string;
52
+ /** App Store / TestFlight / sideload / simulator / web. */
53
+ install_source?: string;
54
+ /** Stable per-install id (iOS IDFV / Android UUID) — first-party, non-tracking. */
55
+ install_id?: string;
56
+ first_install_at?: number;
57
+ last_update_at?: number;
58
+ is_emulator?: boolean;
59
+ device_model?: string;
60
+ device_os?: string;
61
+ device_os_version?: string;
62
+ device_manufacturer?: string;
63
+ device_language?: string;
64
+ device_region?: string;
65
+ push_permission?: string;
66
+ network_type?: string;
67
+ }
68
+
36
69
  export class NativeKit {
37
70
  public readonly haptics = new HapticsModule(this);
38
71
  public readonly share = new ShareModule(this);
@@ -59,11 +92,13 @@ export class NativeKit {
59
92
  public readonly browser = new BrowserModule(this);
60
93
  public readonly oauth = new OAuthModule(this);
61
94
  public readonly billing = new BillingModule(this);
95
+ public readonly updates = new UpdatesModule(this);
62
96
 
63
97
  public handshakeInfo: Handshake | null = null;
64
98
  public options: NativeKitOptions;
65
99
  private adapter: NativeKitAdapter | null = null;
66
100
  private readyPromise: Promise<Handshake> | null = null;
101
+ private contextPromise: Promise<KitContext> | null = null;
67
102
 
68
103
  constructor(options?: Partial<NativeKitOptions>) {
69
104
  this.options = { ...new NativeKitOptions(), ...options };
@@ -88,12 +123,65 @@ export class NativeKit {
88
123
  );
89
124
  }
90
125
  this.handshakeInfo = handshake;
126
+ // Zero-config: a native server-loader app begins polling for remote updates.
127
+ this.updates.__autostart();
91
128
  return this.handshakeInfo;
92
129
  })();
93
130
  }
94
131
  return this.readyPromise;
95
132
  }
96
133
 
134
+ /**
135
+ * One flat analytics bag (handshake + device + install env + push perm + network),
136
+ * ready to spread into super-properties. Resilient: each native probe degrades to
137
+ * omitted on failure, so this never rejects once {@link ready} resolves. Cached.
138
+ */
139
+ context(): Promise<KitContext> {
140
+ if (!this.contextPromise) {
141
+ this.contextPromise = (async () => {
142
+ await this.ready();
143
+ const hs = this.handshakeInfo!;
144
+ const client = this.is.native ? `native-${hs.platform}` : 'web';
145
+ const ctx: KitContext = {
146
+ client,
147
+ is_native: this.is.native,
148
+ platform: hs.platform,
149
+ app_id: hs.app?.id,
150
+ app_name: hs.app?.name,
151
+ app_version: hs.app?.version,
152
+ app_build: hs.app?.build,
153
+ };
154
+ // Probe in parallel; a failing/absent capability simply leaves its fields unset.
155
+ const safe = <T>(p: Promise<T>): Promise<T | null> => p.catch(() => null);
156
+ const [env, device, push, net] = await Promise.all([
157
+ safe(this.app.environment()),
158
+ safe(this.device.info()),
159
+ this.push.capability === 'native' ? safe(this.push.permissionStatus()) : Promise.resolve(null),
160
+ safe(this.network.status()),
161
+ ]);
162
+ if (env) {
163
+ ctx.install_source = env.source;
164
+ ctx.install_id = env.installId;
165
+ ctx.first_install_at = env.firstInstallAt;
166
+ ctx.last_update_at = env.lastUpdateAt;
167
+ ctx.is_emulator = env.isEmulator;
168
+ }
169
+ if (device) {
170
+ ctx.device_model = device.model;
171
+ ctx.device_os = device.os;
172
+ ctx.device_os_version = device.osVersion;
173
+ ctx.device_manufacturer = device.manufacturer;
174
+ ctx.device_language = device.language;
175
+ ctx.device_region = device.region;
176
+ }
177
+ if (push) ctx.push_permission = push;
178
+ if (net) ctx.network_type = net.type;
179
+ return ctx;
180
+ })();
181
+ }
182
+ return this.contextPromise;
183
+ }
184
+
97
185
  get is() {
98
186
  return { native: this.adapter?.kind === 'appwrap', web: this.adapter?.kind === 'web' };
99
187
  }
package/src/core/types.ts CHANGED
@@ -14,6 +14,9 @@ export interface AppInfo {
14
14
  name: string;
15
15
  version: string;
16
16
  build?: string;
17
+ /** How the shell loads content: 'app'/'file' (bundled) or 'server' (remote URL). Drives
18
+ * remote-update detection (only meaningful for 'server'). Absent on web/older shells. */
19
+ loader?: 'app' | 'file' | 'server';
17
20
  }
18
21
 
19
22
  export interface Handshake {
@@ -322,6 +322,17 @@ export class WebAdapter implements NativeKitAdapter {
322
322
  case 'app.openSettings':
323
323
  throw new KitError('UNSUPPORTED', 'No app settings page on web');
324
324
 
325
+ case 'app.environment':
326
+ // On web there's no install — report the honest 'web' source. is_emulator is native-only.
327
+ return { source: 'web', isEmulator: false } as T;
328
+
329
+ case 'push.permissionStatus': {
330
+ // Best-effort via the Notification API (web push ≠ native push, but the perm signal is useful).
331
+ if (!('Notification' in window)) return 'notDetermined' as T;
332
+ const perm = Notification.permission; // 'granted' | 'denied' | 'default'
333
+ return (perm === 'default' ? 'notDetermined' : perm) as T;
334
+ }
335
+
325
336
  case 'billing.products':
326
337
  case 'billing.purchase':
327
338
  case 'billing.restore':
package/src/index.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { NativeKit, NativeKitOptions, kit } from './core/NativeKit';
2
+ export type { KitContext } from './core/NativeKit';
3
+ export type { AppEnvironment, InstallSource } from './modules/app';
2
4
  export { AppwrapAdapter } from './core/appwrap-adapter';
3
5
  export { WebAdapter } from './core/web-adapter';
4
6
  export { KitError } from './core/types';
@@ -29,6 +31,7 @@ export type { AudioMode, MediaDeviceLite } from './modules/media';
29
31
  export type { NetworkStatus } from './modules/network';
30
32
  export type { ActionOptions, AlertOptions, ConfirmOptions, SafeAreaInsets } from './modules/ui';
31
33
  export type { MotionSample } from './modules/motion';
34
+ export type { UpdateStatus, UpdatesOptions } from './modules/updates';
32
35
  export type { PickedContact } from './modules/contacts';
33
36
  export type { CalendarEventOptions } from './modules/calendar';
34
37
  export type { BrowserOptions } from './modules/browser';
@@ -1,5 +1,28 @@
1
1
  import type { NativeKit } from '../core/NativeKit';
2
2
 
3
+ /** Where this build was installed from. Drives beta-vs-prod analytics cohorts.
4
+ * - `appstore` / `playstore` — public store install
5
+ * - `testflight` — iOS beta
6
+ * - `sideload` — direct install (dev build, ad-hoc, APK), or unknown installer
7
+ * - `simulator` — running on a simulator/emulator
8
+ * - `web` — not running inside the native shell */
9
+ export type InstallSource = 'appstore' | 'playstore' | 'testflight' | 'sideload' | 'simulator' | 'web';
10
+
11
+ /** Install-level environment facts the page can't derive itself. First-party,
12
+ * non-tracking (no IDFA/GAID): `installId` is iOS IDFV / an Android UUID kept in
13
+ * app storage — app-scoped and reset on uninstall. */
14
+ export interface AppEnvironment {
15
+ source: InstallSource;
16
+ /** Stable per-install id (iOS identifierForVendor / Android random UUID). */
17
+ installId?: string;
18
+ /** First install epoch-ms (Android only; omitted on iOS — no clean API). */
19
+ firstInstallAt?: number;
20
+ /** Last update epoch-ms (Android only). */
21
+ lastUpdateAt?: number;
22
+ /** Running on a simulator/emulator. */
23
+ isEmulator: boolean;
24
+ }
25
+
3
26
  /** System-level app actions: hand a URL to the OS, or open this app's settings page. */
4
27
  export class AppModule {
5
28
  constructor(private kit: NativeKit) {}
@@ -8,6 +31,11 @@ export class AppModule {
8
31
  return this.kit.capability('app');
9
32
  }
10
33
 
34
+ /** Install-level environment facts for analytics/identification (source, install id, timestamps). */
35
+ environment(): Promise<AppEnvironment> {
36
+ return this.kit.invoke('app.environment');
37
+ }
38
+
11
39
  /** Open a URL in the OS default handler (external browser, mail:, tel:, maps:, …). */
12
40
  openUrl(url: string): Promise<void> {
13
41
  return this.kit.invoke('app.openUrl', { url });
@@ -49,6 +49,12 @@ export class PushModule {
49
49
  return this.kit.invoke('push.requestPermission', undefined, { timeoutMs: 60_000 });
50
50
  }
51
51
 
52
+ /** Current authorization WITHOUT prompting — for opt-in funnel analytics.
53
+ * 'notDetermined' means the user hasn't been asked yet. */
54
+ permissionStatus(): Promise<'granted' | 'denied' | 'notDetermined'> {
55
+ return this.kit.invoke('push.permissionStatus');
56
+ }
57
+
52
58
  /** Register with APNs/FCM and resolve the device token. Call after permission is granted. */
53
59
  register(): Promise<PushToken> {
54
60
  return this.kit.invoke('push.register', undefined, { timeoutMs: 30_000 });
@@ -0,0 +1,164 @@
1
+ import type { NativeKit } from '../core/NativeKit';
2
+ import type { Unsubscribe } from '../core/types';
3
+
4
+ export interface UpdateStatus {
5
+ /** Version the running bundle BOOTED with (embedded), or '' if it couldn't be determined. */
6
+ current: string;
7
+ /** Version advertised by the live manifest, or '' if the fetch failed. */
8
+ latest: string;
9
+ /** Optional build identifier from the manifest. */
10
+ build?: string | number;
11
+ /** True only when both versions are known AND differ — never on an unknown `current`. */
12
+ updateAvailable: boolean;
13
+ }
14
+
15
+ export interface UpdatesOptions {
16
+ /** Version-manifest URL — a tiny JSON `{ version: string, build?: string|number }`.
17
+ * Default: `${location.origin}/version.json`. */
18
+ manifestUrl?: string;
19
+ /** Poll cadence (ms). Always also checks on app resume. 0 = resume-only. Default 60_000. */
20
+ pollIntervalMs?: number;
21
+ /** Version the running bundle booted with. Default: `window.__APP_VERSION__` →
22
+ * `<meta name="app-version">`. Supplying the bundle's OWN embedded version is what
23
+ * makes the prompt trustworthy (see class doc). */
24
+ currentVersion?: string;
25
+ /** Auto-show a persistent native "tap to reload" banner when an update is detected. Default true. */
26
+ autoPrompt?: boolean;
27
+ }
28
+
29
+ /**
30
+ * Remote-update detection for `loader:'server'` apps.
31
+ *
32
+ * Polls a version manifest and compares it to the version the running bundle **booted with**
33
+ * (its embedded `__APP_VERSION__`), NOT to a previous manifest read. That distinction is the
34
+ * whole point: comparing manifest-to-manifest gives a phantom "update available" the moment a
35
+ * deploy bumps the manifest but ships the old bundle (a real bug we've hit). Embedded-vs-manifest
36
+ * only fires when the bytes actually running are behind the deploy.
37
+ *
38
+ * Auto-starts for server-loader native apps (zero app code); apps can also drive it manually via
39
+ * {@link check}/{@link onAvailable}/{@link reload} or re-{@link start} with their own options.
40
+ */
41
+ export class UpdatesModule {
42
+ private started = false;
43
+ private opts: Required<UpdatesOptions> | null = null;
44
+ private timer: ReturnType<typeof setInterval> | null = null;
45
+ private unsubs: Unsubscribe[] = [];
46
+ private listeners = new Set<(s: UpdateStatus) => void>();
47
+ private prompted = false;
48
+
49
+ constructor(private kit: NativeKit) {}
50
+
51
+ get capability() {
52
+ return this.kit.capability('updates');
53
+ }
54
+
55
+ /** Fetch the manifest and compare to the boot version. Reports the result up to the shell
56
+ * (for the dev-menu App Info screen) and fires {@link onAvailable} listeners on a fresh update. */
57
+ async check(): Promise<UpdateStatus> {
58
+ const o = this.opts ?? this.resolveOptions();
59
+ const current = o.currentVersion;
60
+ let latest = '';
61
+ let build: string | number | undefined;
62
+ try {
63
+ // `no-store` skips the HTTP cache — but a cache-first service worker would still intercept and
64
+ // serve a stale manifest, so the SW recipe must let `version.json` pass through to the network.
65
+ const res = await fetch(o.manifestUrl, { cache: 'no-store' });
66
+ if (res.ok) {
67
+ const j = (await res.json()) as { version?: string; build?: string | number };
68
+ latest = String(j?.version ?? '');
69
+ build = j?.build;
70
+ }
71
+ } catch (e) {
72
+ // Offline or no manifest deployed — not fatal; log and report "unknown latest".
73
+ console.warn('[updates] manifest fetch failed:', (e as Error)?.message ?? e);
74
+ }
75
+ const updateAvailable = !!current && !!latest && current !== latest;
76
+ const status: UpdateStatus = { current, latest, build, updateAvailable };
77
+
78
+ // Surface to native so the shake → App Info screen can show "got the latest?".
79
+ this.kit.invoke('app.reportWebVersion', status).catch((e) =>
80
+ console.warn('[updates] reportWebVersion failed:', (e as Error)?.message ?? e)
81
+ );
82
+
83
+ if (updateAvailable) {
84
+ this.listeners.forEach((cb) => cb(status));
85
+ if (o.autoPrompt && !this.prompted) {
86
+ this.prompted = true;
87
+ this.kit
88
+ .invoke('toast.banner', { id: 'appwrap.update', message: 'New version available — tap to reload' })
89
+ .catch((e) => console.warn('[updates] banner failed:', (e as Error)?.message ?? e));
90
+ }
91
+ }
92
+ return status;
93
+ }
94
+
95
+ /** Notify whenever a manifest check finds the running bundle is behind. */
96
+ onAvailable(cb: (s: UpdateStatus) => void): Unsubscribe {
97
+ this.listeners.add(cb);
98
+ return () => this.listeners.delete(cb);
99
+ }
100
+
101
+ /** Hard reload the WebView, bypassing cache (iOS `reloadFromOrigin`, Android cache-clear + reload). */
102
+ reload(): Promise<void> {
103
+ return this.kit.invoke('app.reload');
104
+ }
105
+
106
+ /** Begin polling + resume/banner wiring. Idempotent; re-calling replaces options. */
107
+ start(options?: UpdatesOptions): void {
108
+ this.opts = this.resolveOptions(options);
109
+ if (this.started) {
110
+ this.stop(/* keepStarted */ true);
111
+ }
112
+ this.started = true;
113
+ // A reload picks up the new bundle → allow a fresh prompt next time.
114
+ this.unsubs.push(this.kit.on('app.resume', () => void this.check()));
115
+ // Banner tap (or any 'appwrap.update' action) → reload.
116
+ this.unsubs.push(
117
+ this.kit.on('toast.action', (p) => {
118
+ if ((p as { id?: string })?.id === 'appwrap.update') void this.reload();
119
+ })
120
+ );
121
+ if (this.opts.pollIntervalMs > 0) {
122
+ this.timer = setInterval(() => void this.check(), this.opts.pollIntervalMs);
123
+ }
124
+ void this.check();
125
+ }
126
+
127
+ stop(keepStarted = false): void {
128
+ if (this.timer) clearInterval(this.timer);
129
+ this.timer = null;
130
+ this.unsubs.forEach((u) => u());
131
+ this.unsubs = [];
132
+ if (!keepStarted) this.started = false;
133
+ }
134
+
135
+ /** Called by NativeKit.ready() — self-starts only for a native server-loader app. */
136
+ __autostart(): void {
137
+ if (this.started) return;
138
+ if (this.kit.is.native && this.kit.handshakeInfo?.app?.loader === 'server') this.start();
139
+ }
140
+
141
+ private resolveOptions(o?: UpdatesOptions): Required<UpdatesOptions> {
142
+ const origin = typeof location !== 'undefined' ? location.origin : '';
143
+ return {
144
+ manifestUrl: o?.manifestUrl ?? `${origin}/version.json`,
145
+ pollIntervalMs: o?.pollIntervalMs ?? 60_000,
146
+ currentVersion: o?.currentVersion ?? bootVersion(),
147
+ autoPrompt: o?.autoPrompt ?? true,
148
+ };
149
+ }
150
+ }
151
+
152
+ /** Embedded version the running bundle shipped with: `window.__APP_VERSION__`, then a
153
+ * `<meta name="app-version">` tag. '' (unknown) when neither is present — in which case we never
154
+ * raise a false update prompt. */
155
+ function bootVersion(): string {
156
+ const g = typeof window !== 'undefined' ? (window as any).__APP_VERSION__ : undefined;
157
+ if (g) return String(g);
158
+ if (typeof document !== 'undefined') {
159
+ const meta = document.querySelector('meta[name="app-version"]');
160
+ const c = meta?.getAttribute('content');
161
+ if (c) return c;
162
+ }
163
+ return '';
164
+ }