@astratra/native 0.1.0 → 0.2.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 +159 -2
- package/package.json +7 -3
- package/src/connectivity.js +359 -0
- package/src/index.d.ts +186 -0
- package/src/index.js +4 -1
- package/src/mediaCache.js +262 -0
- package/src/updates.js +196 -0
package/README.md
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
# @astratra/native
|
|
2
2
|
|
|
3
3
|
La plomberie mobile, sans le moteur mobile : **session sécurisée, verrou
|
|
4
|
-
biométrique, notifications natives, retour de paiement
|
|
4
|
+
biométrique, notifications natives, retour de paiement, état du réseau, mises à
|
|
5
|
+
jour à distance, cache de médias**.
|
|
5
6
|
|
|
6
7
|
Le package ne charge ni `expo-secure-store`, ni `expo-local-authentication`,
|
|
7
|
-
ni `expo-web-browser`. Il les **reçoit**. Même règle que `@astratra/notify`
|
|
8
|
+
ni `expo-web-browser`, ni NetInfo, ni `expo-updates`, ni `expo-file-system`. Il les **reçoit**. Même règle que `@astratra/notify`
|
|
8
9
|
avec son transport, et même bénéfice : tout ce qui suit se teste en Node, sans
|
|
9
10
|
simulateur ni build natif.
|
|
10
11
|
|
|
@@ -202,3 +203,159 @@ resolveGlassMode({ platform, apiAvailable, effectAvailable }); // 'native' | 'fa
|
|
|
202
203
|
|
|
203
204
|
Décidé une fois, pour que toutes les surfaces répondent pareil : un en-tête qui
|
|
204
205
|
floute au-dessus d'une carte qui ne floute pas est pire que ni l'un ni l'autre.
|
|
206
|
+
|
|
207
|
+
# Réseau
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
import NetInfo from '@react-native-community/netinfo';
|
|
211
|
+
import { createConnectivityMonitor } from '@astratra/native';
|
|
212
|
+
|
|
213
|
+
export const network = createConnectivityMonitor({ netInfo: NetInfo });
|
|
214
|
+
network.start(); // une fois, au lancement
|
|
215
|
+
network.setRecoveryProbe(() => api.request('/health'));
|
|
216
|
+
|
|
217
|
+
// dans le client HTTP
|
|
218
|
+
if (!network.shouldAttemptRequest()) return fromCache();
|
|
219
|
+
try { const r = await fetch(url); network.noteTransportSuccess(); return r; }
|
|
220
|
+
catch (e) { network.noteTransportFailure(isAbort(e) ? 'timeout' : 'unreachable'); throw e; }
|
|
221
|
+
|
|
222
|
+
// dans un écran
|
|
223
|
+
const offline = useSyncExternalStore(network.subscribe, network.isOffline);
|
|
224
|
+
useEffect(() => network.onComeback(reload), []);
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
**Hors ligne veut dire : aucune interface.** `isConnected === false`, rien
|
|
228
|
+
d'autre. Un `isInternetReachable` à `null` — le système n'a pas encore tranché,
|
|
229
|
+
les premières secondes de chaque lancement — n'est pas une panne : le traiter
|
|
230
|
+
comme tel fait clignoter « hors ligne » à chaque ouverture.
|
|
231
|
+
|
|
232
|
+
**Le « sans Internet » du système n'est pas une panne non plus.** Ce verdict ne
|
|
233
|
+
vient pas de votre serveur : sur Android c'est le drapeau « validé » du Wi-Fi,
|
|
234
|
+
posé seulement après avoir joint un serveur de Google ; ailleurs NetInfo sonde
|
|
235
|
+
lui-même une adresse Google. Sur un Wi-Fi où ce test échoue (DNS du
|
|
236
|
+
fournisseur, filtrage, lenteur), le réseau est déclaré mort alors que les
|
|
237
|
+
requêtes de l'application passent. Constaté en production : l'application se
|
|
238
|
+
disait hors ligne sur le Wi-Fi seul, et ne se croyait en ligne qu'avec les
|
|
239
|
+
données mobiles allumées en même temps. L'état reste donc « inconnu », les
|
|
240
|
+
requêtes partent, et **ce sont elles qui tranchent**.
|
|
241
|
+
|
|
242
|
+
**Un échec de transport se retient trente secondes** (`blackoutMs`). Le cas le
|
|
243
|
+
plus pénible — le Wi-Fi d'hôtel qui accepte la connexion et ne laisse rien
|
|
244
|
+
passer — n'est jamais évident pour le système. Sans cette mémoire, chaque écran
|
|
245
|
+
repayait tout le délai d'expiration avant de montrer son cache ; avec, le
|
|
246
|
+
premier paie, les suivants affichent tout de suite. N'importe quel appel qui
|
|
247
|
+
aboutit l'efface.
|
|
248
|
+
|
|
249
|
+
**Une expiration n'accuse pas toujours le réseau.** Si le système affirme
|
|
250
|
+
qu'Internet est joignable, un serveur lent expire comme un portail captif :
|
|
251
|
+
c'est le serveur qui est en cause, et basculer tout le monde hors ligne
|
|
252
|
+
servirait du cache périmé à tous les écrans. Un refus de transport, lui, est
|
|
253
|
+
formel.
|
|
254
|
+
|
|
255
|
+
**À l'échéance, on repose la question.** Sans cela, rien ne prévenait les
|
|
256
|
+
écrans quand les trente secondes tombaient, et le seul signal de reprise était
|
|
257
|
+
le retour de la radio — qui n'était jamais partie. La sonde part une fois ; si
|
|
258
|
+
elle réussit, la reprise est annoncée, sinon le constat repart. Rien ne part
|
|
259
|
+
quand le système affirme l'absence de réseau.
|
|
260
|
+
|
|
261
|
+
**Le retour du réseau est un événement, pas un état** (`onComeback`) : c'est
|
|
262
|
+
lui qui relance ce qui avait échoué, une seule fois. `refresh()`, pour une
|
|
263
|
+
tâche d'arrière-plan qui se réveille, relit le système sans l'émettre — la
|
|
264
|
+
tâche va vider la file elle-même.
|
|
265
|
+
|
|
266
|
+
**Le lien compte à part** (`getConnectionLink()` : `wifi`, `cellular`, `none`,
|
|
267
|
+
`unknown`). Passer du Wi-Fi aux données mobiles ne change pas « en ligne », et
|
|
268
|
+
change tout pour ce qui se paie au mégaoctet. Traitez `unknown` comme facturé.
|
|
269
|
+
|
|
270
|
+
Les règles sont aussi exportées seules, pures : `readReachability`,
|
|
271
|
+
`readConnectionLink`, `worthAttempting`, `hasComeBack`,
|
|
272
|
+
`shouldDeclareTransportDown`.
|
|
273
|
+
|
|
274
|
+
# Mises à jour à distance
|
|
275
|
+
|
|
276
|
+
```js
|
|
277
|
+
import * as Updates from 'expo-updates';
|
|
278
|
+
import { AppState } from 'react-native';
|
|
279
|
+
import { createUpdateWatcher } from '@astratra/native';
|
|
280
|
+
|
|
281
|
+
const watcher = createUpdateWatcher({
|
|
282
|
+
updates: Updates,
|
|
283
|
+
appState: AppState,
|
|
284
|
+
isOnline: network.shouldAttemptRequest,
|
|
285
|
+
pendingWrites: () => outbox.pending,
|
|
286
|
+
onError: (error, { where }) => report(error, where)
|
|
287
|
+
});
|
|
288
|
+
watcher.start();
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
**Vérifier au lancement, puis au plus une fois par heure** (`checkIntervalMs`),
|
|
292
|
+
au retour au premier plan, et jamais hors ligne. Une mise à jour que
|
|
293
|
+
l'application ne demande jamais ne sert à rien — c'était le cas.
|
|
294
|
+
|
|
295
|
+
**Appliquer seulement quand personne ne regarde.** Au passage en arrière-plan,
|
|
296
|
+
un délai de grâce de 45 secondes (`graceMs`) : répondre à un SMS et revenir
|
|
297
|
+
prend quelques secondes, et recharger pendant cet aller-retour renvoyait la
|
|
298
|
+
personne à l'écran de démarrage, sa page perdue. Revenir annule le délai ; un
|
|
299
|
+
nouveau départ le recommence en entier.
|
|
300
|
+
|
|
301
|
+
**À l'échéance, on revérifie.** Sur iOS, un minuteur gelé en arrière-plan part
|
|
302
|
+
au retour au premier plan, avant l'événement de changement d'état : sans cette
|
|
303
|
+
garde, le rechargement tombait sous les yeux de la personne.
|
|
304
|
+
|
|
305
|
+
**Jamais avec des écritures en attente.** Recharger en pleine reprise de la
|
|
306
|
+
file hors ligne peut rejouer une entrée avant qu'elle soit marquée partie.
|
|
307
|
+
L'occasion suivante la posera.
|
|
308
|
+
|
|
309
|
+
`describeBuild(version)` donne ce que tourne vraiment le téléphone ; son
|
|
310
|
+
`release` (`1.2.0+3f2a9c1d`, ou `1.2.0+embedded`) distingue deux mises à jour du
|
|
311
|
+
même binaire dans les rapports de plantage.
|
|
312
|
+
|
|
313
|
+
# Cache de médias
|
|
314
|
+
|
|
315
|
+
```js
|
|
316
|
+
import * as FileSystem from 'expo-file-system/legacy';
|
|
317
|
+
import { createMediaCache, contentKey, extensionFor } from '@astratra/native';
|
|
318
|
+
|
|
319
|
+
const cache = createMediaCache({
|
|
320
|
+
fs: FileSystem,
|
|
321
|
+
directory: `${FileSystem.cacheDirectory}audio/`,
|
|
322
|
+
extensions: ['m4a', 'wav']
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const uri = await cache.resolve(contentKey('v2', lang, text), async () => {
|
|
326
|
+
const response = await api.raw('/speak', { method: 'POST', body });
|
|
327
|
+
const bytes = await response.arrayBuffer();
|
|
328
|
+
return {
|
|
329
|
+
extension: extensionFor(response.headers.get('content-type'), { 'audio/mp4': 'm4a' }, 'wav'),
|
|
330
|
+
write: (tempUri) => FileSystem.writeAsStringAsync(tempUri, toBase64(bytes), { encoding: 'base64' })
|
|
331
|
+
};
|
|
332
|
+
});
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
La première version de ce cache retéléchargeait tout le fichier à chaque
|
|
336
|
+
lecture, et laissait chaque copie sous un nom horodaté que plus rien ne
|
|
337
|
+
relisait : le dossier grossissait sans fin.
|
|
338
|
+
|
|
339
|
+
**Une clé stable par contenu.** `contentKey(...parties)` : tout ce qui change
|
|
340
|
+
les octets, **version comprise** — quand le serveur change son rendu, la
|
|
341
|
+
nouvelle version retire les anciens fichiers. Les parties sont encodées, pas
|
|
342
|
+
collées : `('a:b', 'c')` et `('a', 'b:c')` ne partagent pas de clé. 106 bits,
|
|
343
|
+
en JS pur (une empreinte native serait asynchrone et ne tournerait pas en Node).
|
|
344
|
+
|
|
345
|
+
**Écrire à côté, puis déplacer.** Une coupure au milieu de l'écriture laisse un
|
|
346
|
+
`.tmp`, jamais un fichier tronqué pris pour valide à la lecture suivante. Deux
|
|
347
|
+
appuis sur le même contenu : le déplacement perdant cède au fichier déjà posé.
|
|
348
|
+
|
|
349
|
+
**Un dossier borné** : 40 fichiers et 60 Mo par défaut (`maxFiles`,
|
|
350
|
+
`maxBytes`), les plus anciens partent d'abord. Le plus récent **ne part
|
|
351
|
+
jamais**, même trop lourd à lui seul : c'est celui qu'on lit. Un temporaire de
|
|
352
|
+
plus de cinq minutes (`abandonedAfterMs`) est le reste d'un téléchargement
|
|
353
|
+
coupé ; plus jeune, il est peut-être en cours d'écriture, on n'y touche pas.
|
|
354
|
+
Le rangement suit chaque écriture, sans retenir la lecture, un seul à la fois.
|
|
355
|
+
|
|
356
|
+
Le dossier doit être **à lui seul** : tout ce qui n'y porte pas l'une des
|
|
357
|
+
extensions déclarées est traité comme un temporaire abandonné.
|
|
358
|
+
|
|
359
|
+
L'API historique d'Expo ne sait pas toucher la date d'un fichier sans le
|
|
360
|
+
réécrire : l'éviction suit donc l'ordre de téléchargement, pas celui de
|
|
361
|
+
lecture. Un fichier très relu finit par partir, puis revient au prochain appui.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/native",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching,
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Mobile plumbing without the mobile runtime: secure token session with an injected keystore, a biometric gate, native push registration and foreground watching, a checkout round-trip that survives a missing native module, network state that only calls a missing interface offline, over-the-air updates applied when nobody is looking, and a bounded on-disk media cache. Adapters injected, so it tests in plain Node.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
|
7
7
|
},
|
|
@@ -26,7 +26,11 @@
|
|
|
26
26
|
"expo",
|
|
27
27
|
"session",
|
|
28
28
|
"biometric",
|
|
29
|
-
"push"
|
|
29
|
+
"push",
|
|
30
|
+
"netinfo",
|
|
31
|
+
"offline",
|
|
32
|
+
"expo-updates",
|
|
33
|
+
"cache"
|
|
30
34
|
],
|
|
31
35
|
"license": "MIT",
|
|
32
36
|
"publishConfig": {
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What "online" means, exactly — and who gets to say it.
|
|
3
|
+
*
|
|
4
|
+
* An app with no network signal ends up inferring one from the last request:
|
|
5
|
+
* a status pill that says "offline" when the SERVER fell over, blaming the
|
|
6
|
+
* person's network, and stays green while a request hangs.
|
|
7
|
+
*
|
|
8
|
+
* The OS knows three distinct things, and conflating them is the classic trap:
|
|
9
|
+
*
|
|
10
|
+
* - `isConnected`: an interface is up. A hotel wifi that wants a login page
|
|
11
|
+
* says YES, and nothing gets through.
|
|
12
|
+
* - `isInternetReachable`: the OS's own verdict on the outside world. It is
|
|
13
|
+
* `null` for the first seconds after launch, and — see below — its "no"
|
|
14
|
+
* is about Google, not about us.
|
|
15
|
+
* - the link type (wifi, cellular, none).
|
|
16
|
+
*
|
|
17
|
+
* The rule: offline only when the OS has NO interface at all. Everything else
|
|
18
|
+
* is either proven online or unknown, and unknown lets requests go out. OUR
|
|
19
|
+
* requests are what settle it: a transport failure is remembered for a short
|
|
20
|
+
* while (the blackout below), and a success clears it.
|
|
21
|
+
*
|
|
22
|
+
* NetInfo is INJECTED, like the keystore: importing it here would drag a native
|
|
23
|
+
* module into every test and into every place it is absent.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** Thirty seconds: long enough to spare the next screens the wait, short
|
|
27
|
+
* enough that a passing outage does not condemn the app. */
|
|
28
|
+
const TRANSPORT_BLACKOUT_MS = 30_000;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {{isConnected?: boolean|null, isInternetReachable?: boolean|null}|null|undefined} snapshot
|
|
32
|
+
* @returns {'online'|'offline'|'unknown'} `unknown` is a state of its own, not
|
|
33
|
+
* a default: it lets the UI stay silent instead of announcing an outage it
|
|
34
|
+
* has not observed.
|
|
35
|
+
*/
|
|
36
|
+
function readReachability(snapshot) {
|
|
37
|
+
if (!snapshot) return 'unknown';
|
|
38
|
+
|
|
39
|
+
/* No interface at all: the only case where the OS is certain without having
|
|
40
|
+
to reach anything. */
|
|
41
|
+
if (snapshot.isConnected === false) return 'offline';
|
|
42
|
+
|
|
43
|
+
/* An interface the OS calls "no Internet" is NOT proof of an outage. Seen in
|
|
44
|
+
production: that verdict does not come from our server. On Android it is
|
|
45
|
+
the wifi's "validated" flag, set only after reaching a Google endpoint;
|
|
46
|
+
elsewhere NetInfo probes a Google URL itself. On a wifi where that test
|
|
47
|
+
fails (provider DNS, filtering, slowness) the network is declared dead
|
|
48
|
+
while the app's own requests go through: the app showed "offline" on
|
|
49
|
+
wifi alone, and believed itself online only with mobile data switched on
|
|
50
|
+
too (the OS then validated through 4G).
|
|
51
|
+
|
|
52
|
+
So it stays unknown, requests go out, and a real failure is caught by the
|
|
53
|
+
transport blackout. Captive portals and exhausted data plans are still
|
|
54
|
+
detected — by the failure itself, not by Google's probe. */
|
|
55
|
+
if (snapshot.isInternetReachable === false) return 'unknown';
|
|
56
|
+
|
|
57
|
+
if (snapshot.isConnected === true && snapshot.isInternetReachable === true) return 'online';
|
|
58
|
+
|
|
59
|
+
/* Interface up, verdict not rendered yet. Treating that as an outage would
|
|
60
|
+
flash "offline" on every launch and teach people to ignore the pill. */
|
|
61
|
+
return 'unknown';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The current link, from the point of view of what it COSTS.
|
|
66
|
+
*
|
|
67
|
+
* Not the same question as "are we online": a download on home wifi is free,
|
|
68
|
+
* the same one on mobile data is paid by the megabyte. Ethernet and a docked
|
|
69
|
+
* tablet's wifi sit on the same side; whatever cannot be named is `unknown`,
|
|
70
|
+
* and callers should treat unknown as metered.
|
|
71
|
+
*
|
|
72
|
+
* @returns {'wifi'|'cellular'|'none'|'unknown'}
|
|
73
|
+
*/
|
|
74
|
+
function readConnectionLink(snapshot) {
|
|
75
|
+
if (!snapshot) return 'unknown';
|
|
76
|
+
if (readReachability(snapshot) === 'offline') return 'none';
|
|
77
|
+
const type = String(snapshot.type ?? '').toLowerCase();
|
|
78
|
+
if (type === 'wifi' || type === 'ethernet' || type === 'wimax') return 'wifi';
|
|
79
|
+
if (type === 'cellular') return 'cellular';
|
|
80
|
+
if (type === 'none') return 'none';
|
|
81
|
+
return 'unknown';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Should an outage be announced? Only an established one. */
|
|
85
|
+
function isDefinitelyOffline(snapshot) {
|
|
86
|
+
return readReachability(snapshot) === 'offline';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Is a request worth attempting? Yes, unless certain otherwise. Blocking on
|
|
91
|
+
* `unknown` would stop the app from starting during the seconds the OS has not
|
|
92
|
+
* decided yet — that is, on every launch.
|
|
93
|
+
*/
|
|
94
|
+
function worthAttempting(snapshot) {
|
|
95
|
+
return readReachability(snapshot) !== 'offline';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Did the network just come back? That transition, and only it, should trigger
|
|
100
|
+
* a reload. Reacting to "we are online" would refire every request on each OS
|
|
101
|
+
* notification, including when nothing changed.
|
|
102
|
+
*/
|
|
103
|
+
function hasComeBack(previous, next) {
|
|
104
|
+
return previous === 'offline' && next === 'online';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Does a failed request prove the NETWORK is down?
|
|
109
|
+
*
|
|
110
|
+
* The blackout stops EVERY request: it must only be raised when the network is
|
|
111
|
+
* to blame. A server taking longer than the timeout — peak hour, a heavy
|
|
112
|
+
* endpoint — expires exactly like a captive wifi. The OS knows the difference:
|
|
113
|
+
* when it AFFIRMS the Internet is reachable, a timeout blames the server, and
|
|
114
|
+
* flipping the app offline on a healthy connection would serve stale cache to
|
|
115
|
+
* every screen.
|
|
116
|
+
*
|
|
117
|
+
* A transport refusal ("Network request failed") is conclusive whatever the OS
|
|
118
|
+
* says: the request never left.
|
|
119
|
+
*
|
|
120
|
+
* @param {{reason: 'timeout'|'unreachable', reachability: 'online'|'offline'|'unknown'}} input
|
|
121
|
+
*/
|
|
122
|
+
function shouldDeclareTransportDown({ reason, reachability } = {}) {
|
|
123
|
+
if (reason === 'unreachable') return true;
|
|
124
|
+
return reachability !== 'online';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** NetInfo's state, narrowed to what the rules read. */
|
|
128
|
+
function toSnapshot(state) {
|
|
129
|
+
const source = state || {};
|
|
130
|
+
return {
|
|
131
|
+
isConnected: source.isConnected ?? null,
|
|
132
|
+
isInternetReachable: source.isInternetReachable ?? null,
|
|
133
|
+
type: source.type ?? null
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* One subscription to the OS for the whole app.
|
|
139
|
+
*
|
|
140
|
+
* Every screen with its own NetInfo listener keeps the radio busy for nothing,
|
|
141
|
+
* and on an entry-level phone that is paid in battery. Screens subscribe to
|
|
142
|
+
* this monitor, not to the OS.
|
|
143
|
+
*
|
|
144
|
+
* @param {object} [options]
|
|
145
|
+
* @param {{addEventListener: Function, fetch: Function}} [options.netInfo]
|
|
146
|
+
* @react-native-community/netinfo's default export, or anything shaped like
|
|
147
|
+
* it. Only needed for start() and refresh().
|
|
148
|
+
* @param {number} [options.blackoutMs] How long a transport failure is
|
|
149
|
+
* remembered.
|
|
150
|
+
* @param {() => number} [options.now]
|
|
151
|
+
*/
|
|
152
|
+
function createConnectivityMonitor(options = {}) {
|
|
153
|
+
const netInfo = options.netInfo || null;
|
|
154
|
+
const blackoutMs = Number.isFinite(options.blackoutMs) ? options.blackoutMs : TRANSPORT_BLACKOUT_MS;
|
|
155
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
156
|
+
|
|
157
|
+
let snapshot = null;
|
|
158
|
+
let reachability = 'unknown';
|
|
159
|
+
let unsubscribeNetInfo = null;
|
|
160
|
+
|
|
161
|
+
const listeners = new Set();
|
|
162
|
+
const comebackListeners = new Set();
|
|
163
|
+
|
|
164
|
+
let transportDownUntil = 0;
|
|
165
|
+
let blackoutTimer = null;
|
|
166
|
+
let recoveryProbe = null;
|
|
167
|
+
|
|
168
|
+
function notifyAll() {
|
|
169
|
+
for (const notify of [...listeners]) notify();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function notifyComeback() {
|
|
173
|
+
for (const notify of [...comebackListeners]) notify();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function clearTransportDown() {
|
|
177
|
+
transportDownUntil = 0;
|
|
178
|
+
if (blackoutTimer) clearTimeout(blackoutTimer);
|
|
179
|
+
blackoutTimer = null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function publish(next, emitComeback = true) {
|
|
183
|
+
const previous = reachability;
|
|
184
|
+
/* The link TYPE counts separately: moving from wifi to mobile data leaves
|
|
185
|
+
"online" unchanged, and changes everything for what is paid by the
|
|
186
|
+
megabyte. Without this second witness, a settings screen kept announcing
|
|
187
|
+
wifi after the person left the house. */
|
|
188
|
+
const previousLink = readConnectionLink(snapshot);
|
|
189
|
+
snapshot = next;
|
|
190
|
+
reachability = readReachability(next);
|
|
191
|
+
if (previous === reachability && previousLink === readConnectionLink(next)) return;
|
|
192
|
+
|
|
193
|
+
notifyAll();
|
|
194
|
+
/* The return of the network is an EVENT, not a state: it restarts what had
|
|
195
|
+
failed, once. What we had observed no longer holds. */
|
|
196
|
+
if (hasComeBack(previous, reachability)) {
|
|
197
|
+
clearTransportDown();
|
|
198
|
+
if (emitComeback) notifyComeback();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The end of the blackout, and the question put back to the server.
|
|
204
|
+
*
|
|
205
|
+
* The blackout used to be read off the clock, and nobody was told when it
|
|
206
|
+
* lapsed: a status bell sat on "offline" until something else repainted it,
|
|
207
|
+
* and screens that had fallen back to cache stayed there, since the only
|
|
208
|
+
* recovery signal was the RADIO coming back — and it had never left. Seen
|
|
209
|
+
* against a dev server restarted by a file watcher several times a minute:
|
|
210
|
+
* each restart refused one connection, and the app believed itself offline
|
|
211
|
+
* long after the server answered again.
|
|
212
|
+
*
|
|
213
|
+
* So at expiry the screens are told, and ONE light request goes to the
|
|
214
|
+
* server. If it succeeds, noteTransportSuccess() announces the recovery; if
|
|
215
|
+
* it fails, the blackout restarts. Nothing is sent while the OS affirms
|
|
216
|
+
* there is no network: its own return will take care of it.
|
|
217
|
+
*/
|
|
218
|
+
function armBlackoutTimer() {
|
|
219
|
+
if (blackoutTimer) clearTimeout(blackoutTimer);
|
|
220
|
+
blackoutTimer = setTimeout(() => {
|
|
221
|
+
blackoutTimer = null;
|
|
222
|
+
notifyAll();
|
|
223
|
+
if (reachability !== 'offline' && recoveryProbe) {
|
|
224
|
+
Promise.resolve()
|
|
225
|
+
.then(() => recoveryProbe())
|
|
226
|
+
.catch(() => undefined);
|
|
227
|
+
}
|
|
228
|
+
}, blackoutMs);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function isTransportDown() {
|
|
232
|
+
return now() < transportDownUntil;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* A request failed in transport. Remember it: the case that hurts most is
|
|
237
|
+
* never obvious to the OS — the wifi that accepts the connection and lets
|
|
238
|
+
* nothing through. `isInternetReachable` stays null there, and every screen
|
|
239
|
+
* paid the full request timeout before showing its cache. With the
|
|
240
|
+
* blackout, the first screen pays the wait, the next ones show cache at once.
|
|
241
|
+
*
|
|
242
|
+
* @param {'timeout'|'unreachable'} [reason]
|
|
243
|
+
*/
|
|
244
|
+
function noteTransportFailure(reason = 'unreachable') {
|
|
245
|
+
/* A timeout on a network the OS calls healthy blames the server, not the
|
|
246
|
+
connection: it does not cut everyone's requests for thirty seconds. */
|
|
247
|
+
if (!shouldDeclareTransportDown({ reason, reachability })) return;
|
|
248
|
+
/* Compared to the clock, not to zero: an expired blackout leaves its date
|
|
249
|
+
behind, and a `!transportDownUntil` test silenced the next outage. */
|
|
250
|
+
const wasDown = isTransportDown();
|
|
251
|
+
transportDownUntil = now() + blackoutMs;
|
|
252
|
+
armBlackoutTimer();
|
|
253
|
+
/* The blackout is news: a screen open for an hour must learn it without
|
|
254
|
+
having asked anything itself. */
|
|
255
|
+
if (!wasDown) notifyAll();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Any request that got an answer. Clears the blackout and, if there was one,
|
|
259
|
+
* announces the recovery like the radio's own return would. */
|
|
260
|
+
function noteTransportSuccess() {
|
|
261
|
+
if (!transportDownUntil) return;
|
|
262
|
+
clearTransportDown();
|
|
263
|
+
notifyAll();
|
|
264
|
+
if (reachability !== 'offline') notifyComeback();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function onNetInfoState(state) {
|
|
268
|
+
publish(toSnapshot(state));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
/** Start listening to the OS. Idempotent: a second call does nothing. */
|
|
273
|
+
start() {
|
|
274
|
+
if (unsubscribeNetInfo) return;
|
|
275
|
+
if (!netInfo) throw new Error('createConnectivityMonitor: start() needs a netInfo adapter.');
|
|
276
|
+
const subscription = netInfo.addEventListener(onNetInfoState);
|
|
277
|
+
unsubscribeNetInfo = typeof subscription === 'function'
|
|
278
|
+
? subscription
|
|
279
|
+
: () => subscription && typeof subscription.remove === 'function' && subscription.remove();
|
|
280
|
+
Promise.resolve()
|
|
281
|
+
.then(() => netInfo.fetch())
|
|
282
|
+
.then(onNetInfoState)
|
|
283
|
+
.catch(() => undefined);
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
stop() {
|
|
287
|
+
if (unsubscribeNetInfo) unsubscribeNetInfo();
|
|
288
|
+
unsubscribeNetInfo = null;
|
|
289
|
+
clearTransportDown();
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Re-read the OS, for a background task waking from suspension: the last
|
|
294
|
+
* known state may be frozen. The comeback event is NOT emitted — it would
|
|
295
|
+
* start a second flush alongside the one the background task is about to
|
|
296
|
+
* run itself.
|
|
297
|
+
* @returns {Promise<boolean>} Whether a request is worth attempting.
|
|
298
|
+
*/
|
|
299
|
+
async refresh() {
|
|
300
|
+
if (!netInfo) throw new Error('createConnectivityMonitor: refresh() needs a netInfo adapter.');
|
|
301
|
+
publish(toSnapshot(await netInfo.fetch()), false);
|
|
302
|
+
return worthAttempting(snapshot);
|
|
303
|
+
},
|
|
304
|
+
|
|
305
|
+
/** Feed a state by hand — tests, or a platform with its own source. */
|
|
306
|
+
setSnapshot(next) {
|
|
307
|
+
publish(toSnapshot(next));
|
|
308
|
+
},
|
|
309
|
+
|
|
310
|
+
getReachability: () => reachability,
|
|
311
|
+
getConnectionLink: () => readConnectionLink(snapshot),
|
|
312
|
+
isTransportDown,
|
|
313
|
+
|
|
314
|
+
/** One answer for the whole app: the OS affirms no network, or the app has
|
|
315
|
+
* just observed that nothing gets through. */
|
|
316
|
+
isOffline: () => reachability === 'offline' || isTransportDown(),
|
|
317
|
+
|
|
318
|
+
/** A blackout just observed is a certainty, even before the OS decides. */
|
|
319
|
+
shouldAttemptRequest: () => !isTransportDown() && worthAttempting(snapshot),
|
|
320
|
+
|
|
321
|
+
noteTransportFailure,
|
|
322
|
+
noteTransportSuccess,
|
|
323
|
+
|
|
324
|
+
/** The light request fired when a blackout lapses. Null disables it. */
|
|
325
|
+
setRecoveryProbe(probe) {
|
|
326
|
+
recoveryProbe = typeof probe === 'function' ? probe : null;
|
|
327
|
+
},
|
|
328
|
+
|
|
329
|
+
/** Any change of state or link. Shaped for useSyncExternalStore. */
|
|
330
|
+
subscribe(listener) {
|
|
331
|
+
listeners.add(listener);
|
|
332
|
+
return () => {
|
|
333
|
+
listeners.delete(listener);
|
|
334
|
+
};
|
|
335
|
+
},
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The network came BACK. Separate from subscribe(): a screen that reloads
|
|
339
|
+
* on recovery has no reason to re-render on every OS heartbeat.
|
|
340
|
+
*/
|
|
341
|
+
onComeback(listener) {
|
|
342
|
+
comebackListeners.add(listener);
|
|
343
|
+
return () => {
|
|
344
|
+
comebackListeners.delete(listener);
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
module.exports = {
|
|
351
|
+
TRANSPORT_BLACKOUT_MS,
|
|
352
|
+
readReachability,
|
|
353
|
+
readConnectionLink,
|
|
354
|
+
isDefinitelyOffline,
|
|
355
|
+
worthAttempting,
|
|
356
|
+
hasComeBack,
|
|
357
|
+
shouldDeclareTransportDown,
|
|
358
|
+
createConnectivityMonitor
|
|
359
|
+
};
|
package/src/index.d.ts
CHANGED
|
@@ -280,3 +280,189 @@ export function createApiClient(options: {
|
|
|
280
280
|
refreshPath?: string;
|
|
281
281
|
onSessionExpired?: (cause: unknown) => void;
|
|
282
282
|
}): ApiClient;
|
|
283
|
+
|
|
284
|
+
/* ───────────────────────────── Connectivity ──────────────────────────── */
|
|
285
|
+
|
|
286
|
+
/** What the OS reports, narrowed to what the rules read. NetInfo's state fits. */
|
|
287
|
+
export interface NetworkSnapshot {
|
|
288
|
+
isConnected?: boolean | null;
|
|
289
|
+
isInternetReachable?: boolean | null;
|
|
290
|
+
type?: string | null;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export type Reachability = 'online' | 'offline' | 'unknown';
|
|
294
|
+
export type ConnectionLink = 'wifi' | 'cellular' | 'none' | 'unknown';
|
|
295
|
+
export type TransportFailure = 'timeout' | 'unreachable';
|
|
296
|
+
|
|
297
|
+
export const TRANSPORT_BLACKOUT_MS: number;
|
|
298
|
+
|
|
299
|
+
/** Offline ONLY without any interface. The OS "no Internet" stays unknown. */
|
|
300
|
+
export function readReachability(snapshot: NetworkSnapshot | null | undefined): Reachability;
|
|
301
|
+
export function readConnectionLink(snapshot: NetworkSnapshot | null | undefined): ConnectionLink;
|
|
302
|
+
export function isDefinitelyOffline(snapshot: NetworkSnapshot | null | undefined): boolean;
|
|
303
|
+
export function worthAttempting(snapshot: NetworkSnapshot | null | undefined): boolean;
|
|
304
|
+
export function hasComeBack(previous: Reachability, next: Reachability): boolean;
|
|
305
|
+
export function shouldDeclareTransportDown(input: { reason: TransportFailure; reachability: Reachability }): boolean;
|
|
306
|
+
|
|
307
|
+
/** @react-native-community/netinfo's default export, narrowed. */
|
|
308
|
+
export interface NetInfoLike {
|
|
309
|
+
addEventListener(listener: (state: NetworkSnapshot) => void): (() => void) | { remove(): void };
|
|
310
|
+
fetch(): Promise<NetworkSnapshot>;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export interface ConnectivityMonitor {
|
|
314
|
+
start(): void;
|
|
315
|
+
stop(): void;
|
|
316
|
+
/** Re-reads the OS without emitting the comeback. Resolves worthAttempting. */
|
|
317
|
+
refresh(): Promise<boolean>;
|
|
318
|
+
setSnapshot(next: NetworkSnapshot | null | undefined): void;
|
|
319
|
+
getReachability(): Reachability;
|
|
320
|
+
getConnectionLink(): ConnectionLink;
|
|
321
|
+
isTransportDown(): boolean;
|
|
322
|
+
isOffline(): boolean;
|
|
323
|
+
shouldAttemptRequest(): boolean;
|
|
324
|
+
noteTransportFailure(reason?: TransportFailure): void;
|
|
325
|
+
noteTransportSuccess(): void;
|
|
326
|
+
setRecoveryProbe(probe: (() => Promise<unknown> | unknown) | null): void;
|
|
327
|
+
/** Shaped for useSyncExternalStore. */
|
|
328
|
+
subscribe(listener: () => void): () => void;
|
|
329
|
+
onComeback(listener: () => void): () => void;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
export function createConnectivityMonitor(options?: {
|
|
333
|
+
netInfo?: NetInfoLike;
|
|
334
|
+
blackoutMs?: number;
|
|
335
|
+
now?: () => number;
|
|
336
|
+
}): ConnectivityMonitor;
|
|
337
|
+
|
|
338
|
+
/* ────────────────────────── Over-the-air updates ─────────────────────── */
|
|
339
|
+
|
|
340
|
+
export const UPDATE_CHECK_INTERVAL_MS: number;
|
|
341
|
+
export const UPDATE_APPLY_GRACE_MS: number;
|
|
342
|
+
|
|
343
|
+
export function shouldCheckForUpdate(
|
|
344
|
+
context: { enabled: boolean; online: boolean; lastCheckAt: number | null; now: number },
|
|
345
|
+
intervalMs?: number
|
|
346
|
+
): boolean;
|
|
347
|
+
|
|
348
|
+
export function shouldApplyUpdate(context: {
|
|
349
|
+
downloaded: boolean;
|
|
350
|
+
stillInBackground: boolean;
|
|
351
|
+
pendingWrites: number;
|
|
352
|
+
}): boolean;
|
|
353
|
+
|
|
354
|
+
export function describeRelease(input: {
|
|
355
|
+
version?: string | null;
|
|
356
|
+
updateId?: string | null;
|
|
357
|
+
isEmbeddedLaunch: boolean;
|
|
358
|
+
}): string;
|
|
359
|
+
|
|
360
|
+
/** expo-updates' module namespace, narrowed to what the watcher uses. */
|
|
361
|
+
export interface UpdatesLike {
|
|
362
|
+
isEnabled: boolean;
|
|
363
|
+
isEmbeddedLaunch: boolean;
|
|
364
|
+
updateId?: string | null;
|
|
365
|
+
channel?: string | null;
|
|
366
|
+
runtimeVersion?: string | null;
|
|
367
|
+
checkForUpdateAsync(): Promise<{ isAvailable: boolean }>;
|
|
368
|
+
fetchUpdateAsync(): Promise<{ isNew: boolean }>;
|
|
369
|
+
reloadAsync(): Promise<void>;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** React Native's AppState, narrowed. */
|
|
373
|
+
export interface AppStateLike {
|
|
374
|
+
currentState: string | null;
|
|
375
|
+
addEventListener(event: 'change', listener: (state: string) => void): { remove(): void } | void;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export interface BuildDescription {
|
|
379
|
+
updateId: string | null;
|
|
380
|
+
channel: string | null;
|
|
381
|
+
runtimeVersion: string | null;
|
|
382
|
+
isEmbeddedLaunch: boolean;
|
|
383
|
+
release: string;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export interface UpdateWatcher {
|
|
387
|
+
start(): void;
|
|
388
|
+
stop(): void;
|
|
389
|
+
/** Resolves true when a new update was downloaded by this call. */
|
|
390
|
+
check(now?: number): Promise<boolean>;
|
|
391
|
+
hasPendingUpdate(): boolean;
|
|
392
|
+
describeBuild(version?: string | null): BuildDescription;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export function createUpdateWatcher(options: {
|
|
396
|
+
updates: UpdatesLike;
|
|
397
|
+
appState: AppStateLike;
|
|
398
|
+
isOnline?: () => boolean;
|
|
399
|
+
pendingWrites?: () => number;
|
|
400
|
+
onError?: (error: unknown, context: { where: 'checkForUpdate' | 'reloadAsync' }) => void;
|
|
401
|
+
checkIntervalMs?: number;
|
|
402
|
+
graceMs?: number;
|
|
403
|
+
now?: () => number;
|
|
404
|
+
}): UpdateWatcher;
|
|
405
|
+
|
|
406
|
+
/* ────────────────────────────── Media cache ──────────────────────────── */
|
|
407
|
+
|
|
408
|
+
export const MEDIA_CACHE_MAX_FILES: number;
|
|
409
|
+
export const MEDIA_CACHE_MAX_BYTES: number;
|
|
410
|
+
export const MEDIA_CACHE_ABANDONED_MS: number;
|
|
411
|
+
|
|
412
|
+
/** [a-z0-9-] only. Every part that changes the bytes — a version included. */
|
|
413
|
+
export function contentKey(...parts: Array<string | number | null | undefined>): string;
|
|
414
|
+
|
|
415
|
+
export function extensionFor(
|
|
416
|
+
contentType: string | null | undefined,
|
|
417
|
+
types: Record<string, string>,
|
|
418
|
+
fallback: string
|
|
419
|
+
): string;
|
|
420
|
+
|
|
421
|
+
export interface CachedFile {
|
|
422
|
+
name: string;
|
|
423
|
+
/** Bytes. */
|
|
424
|
+
size: number;
|
|
425
|
+
/** Milliseconds. */
|
|
426
|
+
modifiedAt: number;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export function planEviction(
|
|
430
|
+
files: CachedFile[],
|
|
431
|
+
options: {
|
|
432
|
+
extensions: string[];
|
|
433
|
+
maxFiles?: number;
|
|
434
|
+
maxBytes?: number;
|
|
435
|
+
abandonedAfterMs?: number;
|
|
436
|
+
now?: number;
|
|
437
|
+
}
|
|
438
|
+
): string[];
|
|
439
|
+
|
|
440
|
+
/** expo-file-system/legacy's shape, narrowed. `modificationTime` in seconds. */
|
|
441
|
+
export interface FileSystemLike {
|
|
442
|
+
getInfoAsync(uri: string): Promise<{ exists: boolean; isDirectory?: boolean; size?: number; modificationTime?: number }>;
|
|
443
|
+
makeDirectoryAsync(uri: string, options?: { intermediates?: boolean }): Promise<void>;
|
|
444
|
+
moveAsync(options: { from: string; to: string }): Promise<void>;
|
|
445
|
+
deleteAsync(uri: string, options?: { idempotent?: boolean }): Promise<void>;
|
|
446
|
+
readDirectoryAsync(uri: string): Promise<string[]>;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export type MediaWriter = (tempUri: string) => Promise<unknown>;
|
|
450
|
+
|
|
451
|
+
export interface MediaCache {
|
|
452
|
+
readonly directory: string;
|
|
453
|
+
lookup(key: string): Promise<string | null>;
|
|
454
|
+
store(key: string, extension: string, write: MediaWriter): Promise<string>;
|
|
455
|
+
resolve(key: string, download: () => Promise<{ extension: string; write: MediaWriter }>): Promise<string>;
|
|
456
|
+
/** Resolves the names deleted. */
|
|
457
|
+
tidy(): Promise<string[]>;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function createMediaCache(options: {
|
|
461
|
+
fs: FileSystemLike;
|
|
462
|
+
directory: string;
|
|
463
|
+
extensions: string[];
|
|
464
|
+
maxFiles?: number;
|
|
465
|
+
maxBytes?: number;
|
|
466
|
+
abandonedAfterMs?: number;
|
|
467
|
+
now?: () => number;
|
|
468
|
+
}): MediaCache;
|
package/src/index.js
CHANGED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media kept on the phone: fetched once, replayed from disk, bounded.
|
|
3
|
+
*
|
|
4
|
+
* The first version of this cache re-downloaded the WHOLE file on every play,
|
|
5
|
+
* and left each copy behind under a timestamped name that nothing ever read
|
|
6
|
+
* again: the cache directory grew without end. Something already played must
|
|
7
|
+
* replay from disk, instantly and without network, and the directory must stay
|
|
8
|
+
* bounded.
|
|
9
|
+
*
|
|
10
|
+
* Three pieces: a stable name for a piece of content (contentKey), the rule
|
|
11
|
+
* for what to throw away (planEviction), and the gestures on disk
|
|
12
|
+
* (createMediaCache). The file system is INJECTED — expo-file-system's legacy
|
|
13
|
+
* API fits as-is — so all three run in plain Node.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const MEDIA_CACHE_MAX_FILES = 40;
|
|
17
|
+
const MEDIA_CACHE_MAX_BYTES = 60 * 1024 * 1024;
|
|
18
|
+
|
|
19
|
+
/* A temporary file older than this is the remains of an interrupted download
|
|
20
|
+
(app killed, network lost): nobody will finish it. Younger, it may still be
|
|
21
|
+
being written — it is left alone. */
|
|
22
|
+
const MEDIA_CACHE_ABANDONED_MS = 5 * 60 * 1000;
|
|
23
|
+
|
|
24
|
+
const TEMP_SUFFIX = '.tmp';
|
|
25
|
+
|
|
26
|
+
/* cyrb53: a 53-bit pure-JS hash, stable across devices. Run twice with two
|
|
27
|
+
seeds (106 bits): two different contents landing on the same name would
|
|
28
|
+
serve the wrong media, and at that width it does not happen in practice.
|
|
29
|
+
A platform crypto digest would be asynchronous and native — it does not run
|
|
30
|
+
in Node, where this rule is tested. */
|
|
31
|
+
function cyrb53(text, seed) {
|
|
32
|
+
let h1 = 0xdeadbeef ^ seed;
|
|
33
|
+
let h2 = 0x41c6ce57 ^ seed;
|
|
34
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
35
|
+
const code = text.charCodeAt(i);
|
|
36
|
+
h1 = Math.imul(h1 ^ code, 2654435761);
|
|
37
|
+
h2 = Math.imul(h2 ^ code, 1597334677);
|
|
38
|
+
}
|
|
39
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
40
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
41
|
+
return (2097152 * (h2 >>> 0) + (h1 >>> 0)).toString(36);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The file name of a piece of content: every part that changes the bytes.
|
|
46
|
+
*
|
|
47
|
+
* Put a version in the parts. When the server changes how it renders (a new
|
|
48
|
+
* voice, a new codec), files kept under the old key must stop being served,
|
|
49
|
+
* and bumping the version is how they do.
|
|
50
|
+
*
|
|
51
|
+
* The parts are encoded as a JSON array, never joined with a separator:
|
|
52
|
+
* ('a:b', 'c') and ('a', 'b:c') must not share a key.
|
|
53
|
+
*
|
|
54
|
+
* @param {...(string|number|null|undefined)} parts Null and undefined count
|
|
55
|
+
* as empty.
|
|
56
|
+
* @returns {string} [a-z0-9-] only — safe as a file name everywhere.
|
|
57
|
+
*/
|
|
58
|
+
function contentKey(...parts) {
|
|
59
|
+
const source = JSON.stringify(parts.map((part) => (part === null || part === undefined ? '' : String(part))));
|
|
60
|
+
return `${cyrb53(source, 1)}-${cyrb53(source, 2)}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The extension to store a response under, from its Content-Type.
|
|
65
|
+
* @param {string|null|undefined} contentType
|
|
66
|
+
* @param {Record<string, string>} types Lowercase MIME type => extension.
|
|
67
|
+
* @param {string} fallback For anything unlisted — including a missing header.
|
|
68
|
+
*/
|
|
69
|
+
function extensionFor(contentType, types, fallback) {
|
|
70
|
+
const type = String(contentType || '').split(';')[0].trim().toLowerCase();
|
|
71
|
+
const map = types || {};
|
|
72
|
+
return Object.prototype.hasOwnProperty.call(map, type) ? map[type] : fallback;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isFinished(name, extensions) {
|
|
76
|
+
return extensions.some((extension) => name.endsWith(`.${extension}`));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Which files to delete, least recently written first.
|
|
81
|
+
*
|
|
82
|
+
* - a finished file survives while the directory stays under maxFiles AND
|
|
83
|
+
* maxBytes; past either, the oldest go;
|
|
84
|
+
* - the newest is NEVER deleted, even when too heavy on its own: it is the one
|
|
85
|
+
* being played;
|
|
86
|
+
* - anything that is not a finished file (a temporary) goes once abandoned,
|
|
87
|
+
* and does not count against the bounds.
|
|
88
|
+
*
|
|
89
|
+
* @param {Array<{name: string, size: number, modifiedAt: number}>} files
|
|
90
|
+
* `modifiedAt` in milliseconds.
|
|
91
|
+
* @param {object} options
|
|
92
|
+
* @param {string[]} options.extensions What a finished file ends with.
|
|
93
|
+
* @param {number} [options.maxFiles]
|
|
94
|
+
* @param {number} [options.maxBytes]
|
|
95
|
+
* @param {number} [options.abandonedAfterMs]
|
|
96
|
+
* @param {number} [options.now]
|
|
97
|
+
* @returns {string[]}
|
|
98
|
+
*/
|
|
99
|
+
function planEviction(files, options = {}) {
|
|
100
|
+
const extensions = Array.isArray(options.extensions) ? options.extensions : [];
|
|
101
|
+
const maxFiles = Number.isFinite(options.maxFiles) ? options.maxFiles : MEDIA_CACHE_MAX_FILES;
|
|
102
|
+
const maxBytes = Number.isFinite(options.maxBytes) ? options.maxBytes : MEDIA_CACHE_MAX_BYTES;
|
|
103
|
+
const abandonedAfterMs = Number.isFinite(options.abandonedAfterMs) ? options.abandonedAfterMs : MEDIA_CACHE_ABANDONED_MS;
|
|
104
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
105
|
+
|
|
106
|
+
const discard = [];
|
|
107
|
+
const finished = [];
|
|
108
|
+
for (const file of Array.isArray(files) ? files : []) {
|
|
109
|
+
if (!file || typeof file.name !== 'string') continue;
|
|
110
|
+
if (isFinished(file.name, extensions)) finished.push(file);
|
|
111
|
+
else if (now - file.modifiedAt > abandonedAfterMs) discard.push(file.name);
|
|
112
|
+
}
|
|
113
|
+
finished.sort((a, b) => b.modifiedAt - a.modifiedAt);
|
|
114
|
+
let bytes = 0;
|
|
115
|
+
finished.forEach((file, rank) => {
|
|
116
|
+
bytes += Math.max(0, Number(file.size) || 0);
|
|
117
|
+
if (rank === 0) return;
|
|
118
|
+
if (rank >= maxFiles || bytes > maxBytes) discard.push(file.name);
|
|
119
|
+
});
|
|
120
|
+
return discard;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The cache on disk.
|
|
125
|
+
*
|
|
126
|
+
* @param {object} options
|
|
127
|
+
* @param {object} options.fs expo-file-system/legacy's shape: getInfoAsync,
|
|
128
|
+
* makeDirectoryAsync, moveAsync, deleteAsync, readDirectoryAsync.
|
|
129
|
+
* getInfoAsync's `modificationTime` is in SECONDS, as Expo reports it.
|
|
130
|
+
* @param {string} options.directory A directory of its own — anything else
|
|
131
|
+
* found in it is treated as an abandoned temporary and deleted.
|
|
132
|
+
* @param {string[]} options.extensions Every extension a finished file may
|
|
133
|
+
* carry. A lookup tries each.
|
|
134
|
+
* @param {number} [options.maxFiles]
|
|
135
|
+
* @param {number} [options.maxBytes]
|
|
136
|
+
* @param {number} [options.abandonedAfterMs]
|
|
137
|
+
* @param {() => number} [options.now]
|
|
138
|
+
*/
|
|
139
|
+
function createMediaCache(options = {}) {
|
|
140
|
+
const fs = options.fs;
|
|
141
|
+
if (!fs) throw new Error('createMediaCache: an fs adapter is required.');
|
|
142
|
+
if (!options.directory) throw new Error('createMediaCache: a directory is required.');
|
|
143
|
+
const extensions = Array.isArray(options.extensions) ? options.extensions.filter(Boolean) : [];
|
|
144
|
+
if (extensions.length === 0) throw new Error('createMediaCache: at least one extension is required.');
|
|
145
|
+
const directory = options.directory.endsWith('/') ? options.directory : `${options.directory}/`;
|
|
146
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
147
|
+
const bounds = {
|
|
148
|
+
extensions,
|
|
149
|
+
maxFiles: options.maxFiles,
|
|
150
|
+
maxBytes: options.maxBytes,
|
|
151
|
+
abandonedAfterMs: options.abandonedAfterMs
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
let tempCounter = 0;
|
|
155
|
+
let tidying = null;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The finished file for a key, or null.
|
|
159
|
+
*
|
|
160
|
+
* No "last used" date is refreshed on a hit: the legacy API cannot touch a
|
|
161
|
+
* file's date without rewriting it. Eviction therefore follows download
|
|
162
|
+
* order — a file replayed often eventually goes, and comes back on the next
|
|
163
|
+
* play.
|
|
164
|
+
*/
|
|
165
|
+
async function lookup(key) {
|
|
166
|
+
for (const extension of extensions) {
|
|
167
|
+
const uri = `${directory}${key}.${extension}`;
|
|
168
|
+
const info = await fs.getInfoAsync(uri);
|
|
169
|
+
if (info && info.exists) return uri;
|
|
170
|
+
}
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Write under a temporary name, THEN move: an interruption mid-write leaves
|
|
176
|
+
* a .tmp that eviction collects, never a truncated file taken for valid on
|
|
177
|
+
* the next play.
|
|
178
|
+
*
|
|
179
|
+
* @param {string} key
|
|
180
|
+
* @param {string} extension One of `extensions`.
|
|
181
|
+
* @param {(tempUri: string) => Promise<unknown>} write Puts the bytes at
|
|
182
|
+
* tempUri, however the caller's platform writes bytes.
|
|
183
|
+
* @returns {Promise<string>} The finished file's URI.
|
|
184
|
+
*/
|
|
185
|
+
async function store(key, extension, write) {
|
|
186
|
+
if (!extensions.includes(extension)) {
|
|
187
|
+
throw new Error(`createMediaCache: extension "${extension}" is not one of this cache's extensions.`);
|
|
188
|
+
}
|
|
189
|
+
await fs.makeDirectoryAsync(directory, { intermediates: true });
|
|
190
|
+
const destination = `${directory}${key}.${extension}`;
|
|
191
|
+
tempCounter += 1;
|
|
192
|
+
const temporary = `${directory}${key}.${now()}-${tempCounter}${TEMP_SUFFIX}`;
|
|
193
|
+
try {
|
|
194
|
+
await write(temporary);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
await fs.deleteAsync(temporary, { idempotent: true }).catch(() => undefined);
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
await fs.moveAsync({ from: temporary, to: destination });
|
|
201
|
+
} catch (error) {
|
|
202
|
+
/* Two taps on the same content: the other download already put the
|
|
203
|
+
finished file in place. Ours is useless, theirs is valid. */
|
|
204
|
+
await fs.deleteAsync(temporary, { idempotent: true });
|
|
205
|
+
const info = await fs.getInfoAsync(destination);
|
|
206
|
+
if (!info || !info.exists) throw error;
|
|
207
|
+
}
|
|
208
|
+
/* Tidying does not hold up playback: it runs on its own, and its failure
|
|
209
|
+
concerns nobody. */
|
|
210
|
+
void tidy().catch(() => undefined);
|
|
211
|
+
return destination;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The cached file, or a fresh download stored first.
|
|
216
|
+
* @param {string} key
|
|
217
|
+
* @param {() => Promise<{extension: string, write: (tempUri: string) => Promise<unknown>}>} download
|
|
218
|
+
*/
|
|
219
|
+
async function resolve(key, download) {
|
|
220
|
+
const known = await lookup(key);
|
|
221
|
+
if (known) return known;
|
|
222
|
+
const { extension, write } = await download();
|
|
223
|
+
return store(key, extension, write);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/* One tidy at a time: two plays close together must not delete the same
|
|
227
|
+
files twice. */
|
|
228
|
+
function tidy() {
|
|
229
|
+
if (tidying) return tidying;
|
|
230
|
+
tidying = (async () => {
|
|
231
|
+
const info = await fs.getInfoAsync(directory);
|
|
232
|
+
if (!info || !info.exists) return [];
|
|
233
|
+
const names = await fs.readDirectoryAsync(directory);
|
|
234
|
+
const files = [];
|
|
235
|
+
for (const name of names) {
|
|
236
|
+
const entry = await fs.getInfoAsync(`${directory}${name}`);
|
|
237
|
+
if (!entry || !entry.exists || entry.isDirectory) continue;
|
|
238
|
+
files.push({ name, size: Number(entry.size) || 0, modifiedAt: (Number(entry.modificationTime) || 0) * 1000 });
|
|
239
|
+
}
|
|
240
|
+
const discard = planEviction(files, { ...bounds, now: now() });
|
|
241
|
+
for (const name of discard) {
|
|
242
|
+
await fs.deleteAsync(`${directory}${name}`, { idempotent: true });
|
|
243
|
+
}
|
|
244
|
+
return discard;
|
|
245
|
+
})().finally(() => {
|
|
246
|
+
tidying = null;
|
|
247
|
+
});
|
|
248
|
+
return tidying;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return { directory, lookup, store, resolve, tidy };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
module.exports = {
|
|
255
|
+
MEDIA_CACHE_MAX_FILES,
|
|
256
|
+
MEDIA_CACHE_MAX_BYTES,
|
|
257
|
+
MEDIA_CACHE_ABANDONED_MS,
|
|
258
|
+
contentKey,
|
|
259
|
+
extensionFor,
|
|
260
|
+
planEviction,
|
|
261
|
+
createMediaCache
|
|
262
|
+
};
|
package/src/updates.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When to look for an over-the-air update, and when to apply it.
|
|
3
|
+
*
|
|
4
|
+
* Fixing a typo should not cost a store review: that is what remote updates
|
|
5
|
+
* are for. But they are worth nothing if the app never asks for them — the
|
|
6
|
+
* first app this came from never did — and they do harm when applied at the
|
|
7
|
+
* wrong moment: reloading the screen while someone is filling in a payment
|
|
8
|
+
* form loses the form.
|
|
9
|
+
*
|
|
10
|
+
* expo-updates is INJECTED, like the keystore: it is a native module, and the
|
|
11
|
+
* rules below must run in plain Node.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** One hour between checks: more often pays network for nothing. */
|
|
15
|
+
const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The grace period before applying in the background. Answering a text and
|
|
19
|
+
* coming back takes a few seconds: reloading during that round trip sent the
|
|
20
|
+
* person back to the splash screen, their page gone. Past the grace period the
|
|
21
|
+
* absence is a real one — nobody sees the reload.
|
|
22
|
+
*/
|
|
23
|
+
const UPDATE_APPLY_GRACE_MS = 45 * 1000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Should the update server be asked?
|
|
27
|
+
* @param {{enabled: boolean, online: boolean, lastCheckAt: number|null, now: number}} context
|
|
28
|
+
* `enabled` is false for a build without updates (a development client, a
|
|
29
|
+
* build with updates switched off).
|
|
30
|
+
* @param {number} [intervalMs]
|
|
31
|
+
*/
|
|
32
|
+
function shouldCheckForUpdate(context, intervalMs = UPDATE_CHECK_INTERVAL_MS) {
|
|
33
|
+
if (!context || !context.enabled || !context.online) return false;
|
|
34
|
+
if (context.lastCheckAt === null || context.lastCheckAt === undefined) return true;
|
|
35
|
+
return context.now - context.lastCheckAt >= intervalMs;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Reload now? Asked when the grace period lapses, never at the instant the app
|
|
40
|
+
* goes to the background.
|
|
41
|
+
*
|
|
42
|
+
* Never in front of the person — if they are already back, nothing happens —
|
|
43
|
+
* and never with writes still queued: a reload in the middle of flushing the
|
|
44
|
+
* queue could replay an entry before it is marked as sent.
|
|
45
|
+
*
|
|
46
|
+
* @param {{downloaded: boolean, stillInBackground: boolean, pendingWrites: number}} context
|
|
47
|
+
*/
|
|
48
|
+
function shouldApplyUpdate(context) {
|
|
49
|
+
return Boolean(context && context.downloaded && context.stillInBackground && context.pendingWrites === 0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The release name for crash reporting: the binary AND the update it runs. A
|
|
54
|
+
* crash report that names only the store version cannot tell two updates of
|
|
55
|
+
* the same binary apart.
|
|
56
|
+
*/
|
|
57
|
+
function describeRelease({ version, updateId, isEmbeddedLaunch } = {}) {
|
|
58
|
+
const base = version || '0.0.0';
|
|
59
|
+
if (isEmbeddedLaunch || !updateId) return `${base}+embedded`;
|
|
60
|
+
return `${base}+${String(updateId).slice(0, 8)}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Wires the rules to expo-updates and the app state.
|
|
65
|
+
*
|
|
66
|
+
* @param {object} options
|
|
67
|
+
* @param {object} options.updates expo-updates' module namespace: isEnabled,
|
|
68
|
+
* isEmbeddedLaunch, updateId, channel, runtimeVersion, checkForUpdateAsync,
|
|
69
|
+
* fetchUpdateAsync, reloadAsync.
|
|
70
|
+
* @param {{currentState: string, addEventListener: Function}} options.appState
|
|
71
|
+
* React Native's AppState.
|
|
72
|
+
* @param {() => boolean} [options.isOnline] Default: always. Pass the
|
|
73
|
+
* connectivity monitor's shouldAttemptRequest.
|
|
74
|
+
* @param {() => number} [options.pendingWrites] Writes still waiting for the
|
|
75
|
+
* network. Default: none.
|
|
76
|
+
* @param {(error: unknown, context: {where: string}) => void} [options.onError]
|
|
77
|
+
* @param {number} [options.checkIntervalMs]
|
|
78
|
+
* @param {number} [options.graceMs]
|
|
79
|
+
* @param {() => number} [options.now]
|
|
80
|
+
*/
|
|
81
|
+
function createUpdateWatcher(options = {}) {
|
|
82
|
+
const updates = options.updates;
|
|
83
|
+
const appState = options.appState;
|
|
84
|
+
if (!updates) throw new Error('createUpdateWatcher: an updates module is required.');
|
|
85
|
+
if (!appState) throw new Error('createUpdateWatcher: an appState is required.');
|
|
86
|
+
|
|
87
|
+
const isOnline = typeof options.isOnline === 'function' ? options.isOnline : () => true;
|
|
88
|
+
const pendingWrites = typeof options.pendingWrites === 'function' ? options.pendingWrites : () => 0;
|
|
89
|
+
const onError = typeof options.onError === 'function' ? options.onError : () => undefined;
|
|
90
|
+
const checkIntervalMs = Number.isFinite(options.checkIntervalMs) ? options.checkIntervalMs : UPDATE_CHECK_INTERVAL_MS;
|
|
91
|
+
const graceMs = Number.isFinite(options.graceMs) ? options.graceMs : UPDATE_APPLY_GRACE_MS;
|
|
92
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
93
|
+
|
|
94
|
+
let lastCheckAt = null;
|
|
95
|
+
let downloaded = false;
|
|
96
|
+
let applyTimer = null;
|
|
97
|
+
let subscription = null;
|
|
98
|
+
|
|
99
|
+
async function check(at = now()) {
|
|
100
|
+
const due = shouldCheckForUpdate(
|
|
101
|
+
{ enabled: Boolean(updates.isEnabled), online: Boolean(isOnline()), lastCheckAt, now: at },
|
|
102
|
+
checkIntervalMs
|
|
103
|
+
);
|
|
104
|
+
if (!due) return false;
|
|
105
|
+
lastCheckAt = at;
|
|
106
|
+
try {
|
|
107
|
+
const result = await updates.checkForUpdateAsync();
|
|
108
|
+
if (!result || !result.isAvailable) return false;
|
|
109
|
+
const fetched = await updates.fetchUpdateAsync();
|
|
110
|
+
const isNew = Boolean(fetched && fetched.isNew);
|
|
111
|
+
downloaded = downloaded || isNew;
|
|
112
|
+
return isNew;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
/* An unreachable update server is not an app crash; it is reported to be
|
|
115
|
+
seen if it happens often, nothing more. */
|
|
116
|
+
onError(error, { where: 'checkForUpdate' });
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/* When the grace period lapses. On iOS a timer frozen in the background
|
|
122
|
+
fires on return to the foreground: the stillInBackground guard turns that
|
|
123
|
+
late shot into a non-event, never into a reload under the person's eyes. */
|
|
124
|
+
async function applyAfterGrace() {
|
|
125
|
+
applyTimer = null;
|
|
126
|
+
const stillInBackground = appState.currentState !== 'active';
|
|
127
|
+
if (!shouldApplyUpdate({ downloaded, stillInBackground, pendingWrites: Number(pendingWrites()) || 0 })) return;
|
|
128
|
+
downloaded = false;
|
|
129
|
+
try {
|
|
130
|
+
await updates.reloadAsync();
|
|
131
|
+
} catch (error) {
|
|
132
|
+
onError(error, { where: 'reloadAsync' });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function cancelApply() {
|
|
137
|
+
if (applyTimer) clearTimeout(applyTimer);
|
|
138
|
+
applyTimer = null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function onAppStateChange(state) {
|
|
142
|
+
if (state === 'active') {
|
|
143
|
+
/* The person is back: the deferred reload no longer has a reason to be. */
|
|
144
|
+
cancelApply();
|
|
145
|
+
void check();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (state === 'background' && downloaded && !applyTimer) {
|
|
149
|
+
applyTimer = setTimeout(() => void applyAfterGrace(), graceMs);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
/** Call once, when the root mounts. Idempotent. */
|
|
155
|
+
start() {
|
|
156
|
+
if (subscription) return;
|
|
157
|
+
subscription = appState.addEventListener('change', onAppStateChange) || { remove() {} };
|
|
158
|
+
void check();
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
stop() {
|
|
162
|
+
cancelApply();
|
|
163
|
+
if (subscription && typeof subscription.remove === 'function') subscription.remove();
|
|
164
|
+
subscription = null;
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
check,
|
|
168
|
+
|
|
169
|
+
/** Whether an update is downloaded and waiting for the next quiet moment. */
|
|
170
|
+
hasPendingUpdate: () => downloaded,
|
|
171
|
+
|
|
172
|
+
/** What this phone actually runs — for crash reports and a help screen. */
|
|
173
|
+
describeBuild(version) {
|
|
174
|
+
return {
|
|
175
|
+
updateId: updates.updateId ?? null,
|
|
176
|
+
channel: updates.channel ?? null,
|
|
177
|
+
runtimeVersion: updates.runtimeVersion ?? null,
|
|
178
|
+
isEmbeddedLaunch: Boolean(updates.isEmbeddedLaunch),
|
|
179
|
+
release: describeRelease({
|
|
180
|
+
version: version ?? null,
|
|
181
|
+
updateId: updates.updateId,
|
|
182
|
+
isEmbeddedLaunch: updates.isEmbeddedLaunch
|
|
183
|
+
})
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
module.exports = {
|
|
190
|
+
UPDATE_CHECK_INTERVAL_MS,
|
|
191
|
+
UPDATE_APPLY_GRACE_MS,
|
|
192
|
+
shouldCheckForUpdate,
|
|
193
|
+
shouldApplyUpdate,
|
|
194
|
+
describeRelease,
|
|
195
|
+
createUpdateWatcher
|
|
196
|
+
};
|