@voltro/react-native 0.38.0 → 0.39.1

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/CHANGELOG.md CHANGED
@@ -39,6 +39,282 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.39.1] — 2026-08-16
43
+
44
+ ### Fixed
45
+
46
+ - **@voltro/runtime, @voltro/cli** — An app-registered tuple source is no longer replaced by the framework default.
47
+
48
+ Both boot paths carried this comment, verbatim:
49
+
50
+ > An app whose relationships live in its own tables overrides with > `setTupleSource`.
51
+
52
+ and then called `setTupleSource(default)` **unconditionally**. That call runs AFTER the app's startups — `runBootLifecycle` at `dev.ts:3910` and `serveCommand.ts:869`, against the registration at `dev.ts:4065` and `serveApi.ts:937` — and `setTupleSource` is last-write-wins. So the framework won every time: an app registering its own source in a `*.startup.tsx`, which is what the docs tell it to do, had it silently replaced.
53
+
54
+ The consequence is not subtle. Every relationship guard would then be answered from `_voltro_rebac_tuples` — empty, for exactly the app that keeps its relations in its own tables — so every guard DENIES, fail-closed, with a `no tuple source` warning that never fires because a source *is* registered: the wrong one.
55
+
56
+ The comment was not wrong about the design; it described the design while the code removed it. Same shape as the `DORMANCY_WAKEUP_TENANT` scar — equal by value at both call sites, so nothing could fail, and the comment was the only place the intent survived.
57
+
58
+ `registerDefaultTupleSource` fills the gap only when nobody else did, and returns whether it acted so the boot can say which source is live instead of leaving an operator to guess. `setTupleSource` itself is unchanged: an app calling it twice still gets the second one, because narrowing that would trade one silent surprise for another.
59
+
60
+ Found while re-checking a consumer's claim that a different item was still open. It was not — but it sits beside this, and this is the one that would have bitten them. Pinned in both directions: a unit test for the registrar, and a source guard asserting neither boot path installs `loadResourceTuples` through `setTupleSource` again. Red-verified by restoring the original line.
61
+ - **@voltro/cli** — `voltro doctor` no longer reports "scope vocabulary: none found" when it could not read the config at all.
62
+
63
+ A consumer HAD configured `doctor.scopeVocabulary` and still read `none found`. The cause was not their vocabulary: `app.config.ts` could not be imported outside their pod — an auth strategy demands its secret while the config is evaluated — so the vocabulary was never read. Inside the pod the message disappears and the rule runs.
64
+
65
+ "You have no vocabulary" and "I could not look" are different states, and only the first is a statement about their app. This section already made exactly that distinction one member earlier — its own comment reads **DORMANT AND CLEAN MUST NOT PRINT THE SAME** — and then collapsed the third.
66
+
67
+ The signal existed and was not connected. `offlineManifest` deliberately survives an unimportable config (a doctor run must not die on one), so the empty vocabulary arrived looking like a real absence, while the same failure was reported a hundred lines earlier under plugin tables. The consumer read the section about scopes and searched at the wrong end — which is the correct way to read a report.
68
+
69
+ The rule now probes importability before claiming an absence, and says so:
70
+
71
+ ```
72
+ • scope vocabulary: NOT EVALUATED — `app.config.ts` could not be imported.
73
+ This is not a statement about your scopes: the rule never got to read them.
74
+ … The same import failure is reported above for plugin tables; both sections
75
+ have this one cause.
76
+ ```
77
+
78
+ The dormant case keeps its own wording, so a quiet run on an app that genuinely publishes no vocabulary is not relabelled as a broken config.
79
+
80
+ ### Internal (no consumer-facing effect)
81
+
82
+ - **@voltro/cache, @voltro/kv** — The RESP TTL tests in `@voltro/cache` and `@voltro/kv` stopped measuring the machine. Test-only; no product code changed.
83
+
84
+ Both wrote a key with `ttlMs: 150`, asserted it was still there, then slept 300 ms and asserted it was gone. The second half is fine — waiting LONGER only strengthens "it expired". The first half was a race: the write and the read are two round-trips, so on a loaded runner the key legitimately expired before the liveness assertion, and the test reported a defect that was not there. It failed exactly that way on a release gate, in the keydb engine, while passing locally with 24/24 green.
85
+
86
+ Now: a 2 s window, so liveness has real headroom rather than 150 ms of it, and the expiry is awaited as a CONDITION (`awaitGone` polls) rather than as a duration. Idle machines finish in about the TTL; loaded ones take as long as they need; a key that never expires still fails, because the ceiling is a failure mode and not a timing assumption.
87
+
88
+ Fixed in BOTH packages in one change. The two files carried the identical construction, and this repo's standing lesson is that a fix landing in one copy of a duplicated shape leaves the other one broken — `@voltro/kv` had not failed yet, which is a statement about luck rather than about the test.
89
+
90
+ `@voltro/kv`'s header also pointed at `../cache/test/docker-compose.yml` for bringing the engines up. That path does not exist; there is one compose file, at the repo root.
91
+
92
+ ---
93
+
94
+ ## [0.39.0] — 2026-08-16
95
+
96
+ ### Added
97
+
98
+ - **@voltro/client, @voltro/web, @voltro/cli** — A preload that fails server-side now says so in the hydration payload, so a page can tell "still loading" from "actually empty".
99
+
100
+ Reported by a consumer whose session cookie had outlived the IdP's token lifetime — for them, practically every first page view of the day. Every `preload` on the page failed at once, the api having resolved the caller to anonymous:
101
+
102
+ WARN [voltro:dev:web] preload seed failed tag=projects.getById … ScopeError — missing required scope 'project:r:o'
103
+
104
+ The page rendered a skeleton title over an empty table, and that WARN was the only record anywhere. **The client saw exactly what it sees for a page that declares no preload at all** — both arrive as the absence of a seed — so no app could distinguish the two without inventing a convention of its own. The reporting consumer did exactly that, page by page.
105
+
106
+ `usePreloadedSubscription` now returns `preloadFailed: true` in that case:
107
+
108
+ ```tsx
109
+ const projects = usePreloadedSubscription<Project[]>('api', 'projects.list')
110
+
111
+ if (projects.loading) return <Skeleton/>
112
+ if (projects.preloadFailed) return <Spinner label="Loading…"/> // not empty — unasked
113
+ return <Table rows={projects.data}/>
114
+ ```
115
+
116
+ It says nothing about WHY, deliberately: the server's failure text is a refused call's error message and belongs in the server log, which is the one place a browser cannot read. A boolean is the whole contract. It also says nothing about the LIVE subscription, which usually recovers on its own — the browser reconnects with a credential the SSR request did not have. So the honest reading is "the first paint has no server data, and that was not for lack of asking", which is exactly enough to choose a spinner over an empty state.
117
+
118
+ `seedPreloadedSubscriptionFailure` is exported from `@voltro/web/ssr` beside `seedPreloadedSubscription` for a loader that runs its own preloads.
119
+
120
+ Two shape notes, both deliberate:
121
+
122
+ - **The field is widened on THIS hook, not on `SubscriptionState`**, so no existing `useSubscription` call site is un-narrowed by it — the same scoping rule the `skip`/`idle` overload follows. - **`seedFailure` is REQUIRED on the internal preload runner, not optional.** This is the hook whose omission WAS the defect, and an optional hook is an omissible one — the same mistake with a nicer name that cost us `startOutboxRunner`'s teardown. Making it required is what listed all three render paths (dev, start, static prerender) at the compiler rather than at review.
123
+ - **@voltro/web, @voltro/cli** — `LoaderContext.isServer`, and the type now says a loader runs TWICE.
124
+
125
+ Reported after two days of debugging: a loader carried a server-only call, and nothing in `LoaderContext` said the same function runs again in the browser on every in-app navigation. The consumer read "runs once per request" into the gap, which is the reading the wording invited.
126
+
127
+ **The docs were worse than a gap — they contradicted themselves.** The loaders page opened with "the page's server-side data hook" and its first code sample carried the comment `// Server-side fetch — runs on the Node side, never in the browser`, while 230 lines further down the same page said "on a client-side navigation … the loader runs in the browser". A reader who hits the false line first stops looking. Both are corrected, in both languages, and the precondition is now the first thing the page states.
128
+
129
+ **Why it survived two days is the part worth repeating:** a client-only failure is invisible to every probe that does not NAVIGATE. A fresh page load, a `curl`, any SSR check all take the server path and pass. Only clicking a link inside the running app reaches the other one.
130
+
131
+ `ctx.isServer` is the supported discriminator, because the two things that look like they answer the same question do not:
132
+
133
+ - `query` is absent in the browser, so `if (ctx.query)` appears to work — but it branches on the ABSENCE OF A FUNCTION, which says nothing about why it is absent and breaks the moment anything else becomes conditional; - `headers` is `{}` in the browser, **not** `undefined`, so `if (ctx.headers)` is TRUE on both paths. The reporter checked exactly that, and it silently did nothing.
134
+
135
+ It is REQUIRED rather than optional: an optional boolean is omissible, and a server path that forgot it would read as `undefined` — falsy — and claim to be the browser, which is the precise failure the field exists to prevent. The compiler names every client construction site; the three SERVER render paths build their context as untyped literals, so `loaderIsServer.test.ts` derives those by shape and fails on one that omits it (red-verified against a removed line, which named the file and offset).
136
+ - **@voltro/react-native, @voltro/client, @voltro/web, @voltro/cli** — React Native gets the whole client, not half of it. `startMobileApis()` connects and re-dials over the **same** supervisor `@voltro/web` uses — the supervisor moved into `@voltro/client` rather than being copied, because a second copy of its stale-seed gate (the rule that stops one subject's rows appearing in the next subject's screens) is a second thing to keep correct. Web's two browser-specific behaviours are injected options now: the devtools status entry and the dev-only wedge reload.
137
+
138
+ `voltro codegen` in a mobile app writes `.framework/mobileApis.generated.ts` from `voltro.mobile.ts` — which apis the app talks to, and where each one's rpc group and descriptors come from. Only the binding is generated; the procedure types ride the import of the api's own `rpcGroup`, so a schema change needs no regeneration. The ws URL is a runtime parameter and deliberately not baked in: `localhost` on a phone is the phone, and `resolveDevWsUrl()` takes the LAN host Expo already knows.
139
+
140
+ `createAsyncStoragePersistence()` makes `defineStore({ persist })` work on a device. A store reads during render and a render cannot await, so it hydrates into memory once — awaited before the first screen — then serves reads synchronously and writes through, coalescing per tick. A storage with no `getAllKeys()` and no declared `keys` refuses rather than hydrating empty: an empty cache is indistinguishable from a first run.
141
+
142
+ `useMobileConnectionStatus()` takes an optional `onlineSource`. Its default reads `navigator.onLine`, which React Native does not have — so on a device it answered "online" forever, airplane mode included. Pass `netInfoOnlineSource(NetInfo)`. `isInternetReachable` is believed only when it is a boolean, because NetInfo reports `null` while its probe is out and reading that as offline flashes a banner on every cold start.
143
+
144
+ Two type declarations were WRONG, and running the mobile template through the scaffold harness is what said so — nothing else in the repo typechecks a generated entry, on web either.
145
+
146
+ `ClientDescriptorMap` was a structural copy of `@voltro/protocol`'s `ClientDescriptor` that narrowed `source` to one string while the real descriptors carry several. It is now that type, not a copy of it. And an api's `group` is the erased `RpcGroup.Any`: `RpcGroup` is declared `in out` in @effect/rpc, so the CONCRETE group codegen emits was never assignable to `RpcGroup<Rpc.Any>` — the boundary rejected the only value anyone passes it. Erasing at the boundary and restoring at the call site is what `ApiHandle.client` already does; the one cast is where the rpc client is built.
147
+
148
+ `dispatchDeepLink()` is new for the same class of defect. `matchFirstDeepLink` returns a descriptor from a heterogeneous array, so its handler declares `Record<string, never>` params while the match hands back `Record<string, string>` — the result could not be invoked by anyone.
149
+
150
+ `apiSurface: compatible` — every changed declaration either widens what a producer may pass or replaces a type that misdescribed its own values. Code written against the narrow `source` was already wrong at runtime, and no call that compiled before stops compiling. `useMobileConnectionStatus` gained an optional parameter.
151
+
152
+ Not verified here, and not implied: that the loop runs on a device. Everything above is unit-tested without a simulator, and only a simulator can prove Metro. That is an Expo/EAS CI step.
153
+ - **@voltro/runtime** — A `TupleSource` receives the whole `subject`, not just `subjectId`.
154
+
155
+ Reported precisely, from a guard review rather than an outage. `subjectId` cannot express a CREDENTIAL that is narrower than the person holding it, and an API key is exactly that: the key's binding lives in the subject's `metadata` (`keyType`, `teamId`), while `subject.id` is the OWNING USER. A tuple source could therefore only resolve the owner's memberships and was blind to which team the key was minted for — so an owner who belongs to two teams passed the guard for both. The comment beside their hand-written check says what that costs:
156
+
157
+ > Without the binding check below a key minted for team A worked on every team > in the org.
158
+
159
+ Nothing was ever wrong in their app, because they kept the executor-side check. The defect is that a DECLARED guard could not replace it:
160
+
161
+ ```ts
162
+ setTupleSource(async (req) => {
163
+ const boundTeam = req.subject.metadata?.teamId
164
+ if (boundTeam !== undefined && boundTeam !== req.resourceId) return []
165
+ return loadResourceTuples(store, req.subjectId, req.resourceType, req.resourceId)
166
+ })
167
+ ```
168
+
169
+ A guard that must always run paired with a hand-written check is not a declaration — it is a comment with a type signature. And the pairing is exactly the thing nobody re-derives when they delete the "redundant" half a year later; the reporter had already written the reason into their parity test to stop that happening.
170
+
171
+ `subject` is typed as the full union deliberately: its system and anonymous members carry no `scopes` or `metadata`, so the narrowing is the caller's to do and is visible where it happens.
172
+ - **@voltro/cli** — A declared relationship guard whose `resourceType` is not registered now refuses the boot instead of denying every caller forever.
173
+
174
+ The report described the shape exactly: an app arms its authorization from a startup (`defineResourcePolicy` + `setTupleSource`). If that registration does not happen, the app boots **clean**, takes traffic, and every procedure with a declared guard refuses from then on. Fail-closed, so nothing leaks — and a total outage of the guarded surface whose only signal is a log line nobody reads, because the boot was green. At their size: 39 procedures — team settings, hours import, role administration.
175
+
176
+ Since 0.38.0 a `*.startup.tsx` that THROWS already refuses the boot, so the sequence they described is closed. This gate exists because that fix covers only the throwing case, while the same silent outage arrives by three doors no startup-error handling can see:
177
+
178
+ - the startup registers some types and not the one a guard names — a typo in a `resourceType` is not a compile error, it is a string on one side and a string on the other; - the file was renamed out of the discovery pattern, so it never ran and never threw; - the registration was conditional on something false at boot.
179
+
180
+ All three end in the same place, and the framework can rule out all three by asking one question it already holds both halves of: which `resourceType`s does the discovered surface NAME, and which are REGISTERED?
181
+
182
+ The refusal names the type, the count and the procedures that demanded it — grouped by type, because the fix is one `defineResourcePolicy` per type while the damage is per procedure. It also names the spelling trap, since nothing else in the system compares those two strings.
183
+
184
+ **Why refuse rather than warn**, because "fail-closed already, so it is safe" is the plausible objection: safe is not working. The procedures are DOWN, and down-with-a-warning is precisely the state being reported. A refusal is recoverable in seconds and impossible to miss.
185
+
186
+ It runs after the startups have settled, on both boot paths — not beside `assertProcedureAccessDecisions`, which reads declarations and can run at discovery. This one reads a registry the app fills during its startups, and placing it earlier would have failed every app that registers from one, which is all of them. A check that fails on everything gets deleted rather than fixed.
187
+
188
+ ### Fixed
189
+
190
+ - **@voltro/client** — A timer no longer discards the optimistic preview of a write the server confirmed. **A rollback happens if and only if the write FAILED.**
191
+
192
+ Measured by a consumer on a Gantt bar: drag it, the server writes, the mutation reports success — and five seconds later the bar jumps back. They suspected the server first and proved it was holding the data correctly, reasons included, before finding that the client was throwing the confirmed patch away itself.
193
+
194
+ The cause was one line: `confirmByMutation` armed a `setTimeout` calling `revertByMutation` — **the same function the FAILURE path calls**. Success and failure ended in the same discard, one immediately and the other five seconds later.
195
+
196
+ What makes it unambiguous is WHEN that timer could fire at all. Any server event already retires confirmed patches through the seamless hand-off, so the window only ever expired while `base` was still STALE. The revert therefore replaced a value that reflects the committed write with one the client knows does not:
197
+
198
+ | | keep the patch | revert (before) | |---|---|---| | delta arrives later | invisible hand-off | 5s of stale, then a jump back and forth | | delta never arrives | matches what is saved | **contradicts what is saved, permanently** |
199
+
200
+ The bottom-right cell is the damage: the user watches their saved change disappear and either redoes it or plans on a state they believe was not stored. A "leaked" patch is gone on the next subscription; a silent revert is healed by nothing.
201
+
202
+ Expiry is now a **resync**: the client re-issues that subscription, keeps the patch, and says so loudly on the error bus (`voltro logs`) — the silence was the second half of the report, because in the UI this is indistinguishable from "the server did not save it", which is the false trail they followed first.
203
+
204
+ **Two more seams of the same defect, both found while fixing it:**
205
+
206
+ - **An `error` event retired confirmed patches.** An error does not advance `base` — it sets `baseError` and leaves the rows where they were — so dropping there discarded a committed write's preview for nothing. - **A resync whose snapshot comes back UNCHANGED must not retire them either.** The first version of this fix had exactly that hole: it re-asked the server, the answer was byte-identical, and the patch was dropped anyway — the reported bug reached by a longer route. The hand-off rule is now explicit (`supersedesConfirmedPatches`): a delta always supersedes, an error never does, and a snapshot only when it actually MOVED the base.
207
+
208
+ The rule is pinned against the source, not only behaviourally: no `setTimeout` in the cache may name a revert. The defect was never inside a function — it was which function a timer pointed at, and a behavioural test only sees that if somebody thought to write the case. Nobody had: `CONFIRMED_PATCH_TTL_MS` was named nowhere in the test file, which the reporter also pointed out. It is now, red-verified by restoring the original line.
209
+ - **@voltro/ui-shadcn** — `AnimatedNumber` rendered `0` into static markup. It initialised its state to zero and counted up on hydration, so every statically rendered page SHIPPED the zero — the landing site's own stats row went out as "0 … 0 … 0% … 0", which is what a crawler, an answer engine and any reader with JavaScript off saw. A number that only exists after hydration is not a number on the page.
210
+
211
+ It now renders the target value (so the server's markup and the first client render agree — no hydration mismatch) and drops to zero inside the observer callback, at the one moment the animation is actually about to run. The count-up is decoration layered on a correct page rather than the only way to see the value.
212
+
213
+ The test that covered this asserted `toBe('0')` before scrolling — it was pinning the defect. It asserts the final value now, with the reason written next to it, plus a second case for the count-up itself.
214
+
215
+ `CodeCompare`'s corner tags take an `eyebrow` prop instead of hardcoding "Before" / "With Voltro". This kit renders a bilingual site, and an English label over German copy is the same defect as any other hardcoded string. The English default keeps every existing call working.
216
+ - **@voltro/cli** — `voltro dev` reports the db-pool budget too, and the out-of-pool count is right on every dialect.
217
+
218
+ The line was `voltro serve`-only, and the module said so with its reasoning: a dev machine has one process and no replicas, so `max × replicas` is noise. It even asked a future reader not to "fix the parity gap" by moving it.
219
+
220
+ The reasoning was fine and its PREMISE was false. `voltro dev` is not always a dev machine — at least one consumer runs it as their deployment, two API pods against a shared pooler, and `retentionSweep.ts` already reasons about that same consumer in its own header. Two modules cannot both be right about what `voltro dev` is. The cost was not theoretical: that consumer REPORTED the out-of-pool `LISTEN` connection, we answered it in this line, and they could not see the answer, because the one boot path they run does not print it.
221
+
222
+ So the exception is conditional rather than per-command now. `voltro serve` always reports; `voltro dev` reports when the environment shows the process is not a laptop — `REPLICA_COUNT` (a process cannot know how many of itself are running, so a platform set it), `DB_MAX_CONNECTIONS` / `PG_MAX_CONNECTIONS` (somebody is already reasoning about this number), or `DB_REPLICA_URLS` (which multiplies the pools inside ONE process — the case most likely to be mis-budgeted, because it does not look like a fleet). A bare `voltro dev` with nothing set stays silent, which is the half of the original decision that was right.
223
+
224
+ **And the out-of-pool arithmetic was wrong for two dialects.** It was derived inline as `dialect === 'postgres' && CDC !== '0'`. The mysql/mariadb ROW-binlog reader speaks the REPLICATION protocol, which is a separate connection from the SQL pool by construction, so a mariadb deployment read a line that under-reported its own process by one. It is counted now. mssql Change Tracking is NOT counted, and that zero is verified rather than omitted — it reads through the store's own `SqlClient` and its module says "the CT reader needs no second pool".
225
+
226
+ Both boot paths go through one `reportDbPoolLine`, and the CDC derivation takes the ARMED state as a parameter instead of re-reading the env: a binlog reader stands down when every app table is `.nonReactive()`, and billing a connection nobody opened is the same class of error as missing one.
227
+ - **@voltro/cli** — The 0.37.0 strict-input note under-sold the one case that breaks hardest, and the correction is RE-ISSUED rather than edited.
228
+
229
+ 0.37.0 made an undeclared input field reject the call. Its note described the general case correctly and then, under WHAT DOES NOT CHANGE, said "an empty input to a procedure that declares none is still fine". True about sending `{}`, and it reads as reassurance to the owner of an `input: Schema.Struct({})` — whose procedure is the one shape that did NOT move from "silently drops the extra field" to "rejects it". It moved from accepting EVERYTHING to accepting nothing, because an empty `TypeLiteral` has no expected keys for excess-property checking to compare against. The strongest-looking declaration was the only one enforcing nothing.
230
+
231
+ A consumer measured the upgrade across 2 705 procedures and found three real breaks. The most expensive was exactly this: a `getMy` declaring `Schema.Struct({})` while a shared table hook always sent `{ limit }`. Before, the limit was discarded and the call worked; after, the live subscription AND the SSR seed of that page both die.
232
+
233
+ **Why a new codemod and not an edit.** `selectCodemods` filters `from < version <= to`, so anyone who has already crossed 0.37.0 — including the consumer who reported this — will never see that note again, whatever it says. A correction filed there reaches only users who have not upgraded yet, i.e. not the ones holding the broken app. `0.39.0/01_empty-input-schema-rejects-every-field` carries it to the people who need it. (The 0.37.0 note is corrected too, for users still short of it. That edit is necessary and not sufficient, and the difference between those two words is why there are two files.)
234
+
235
+ Its `appliesTo` is deliberately BROADER than the original's. 0.37.0's fires on a spread into a procedure input or the untyped string form of `ctx.query` — the constructs that carry a field the author never typed, which is the right gate for the general case and the wrong one here. The payload does not have to be invisible for this to break: the reporting consumer reached it through an untyped wrapper hook passing an explicit `{ limit }`. So this one gates on the DECLARATION — an empty struct anywhere in the app — which is the population that actually changed behaviour.
236
+ - **@voltro/cli** — All three ways a mutating inspect request can be refused now name the variable, the header, AND where the value comes from.
237
+
238
+ A consumer verifying a row filter hit this one:
239
+
240
+ 401 {"error":"unauthorized","reason":"inspect: POST needs the write credential — send it as the `x-voltro-inspect-write` header alongside the bearer. The read token authorises reads only."}
241
+
242
+ Their words for it: the message is good, and the missing half is **where the value comes from**. They knew what to send and not what to send AS. They gave up on our tooling and hand-signed a session token instead.
243
+
244
+ That half is exactly the part a user cannot guess, because in dev nobody ever typed it: `voltro dev` MINTS `VOLTRO_INSPECT_WRITE_TOKEN` into the project's gitignored `.env.local`. Every arm says so now.
245
+
246
+ **It is a function over the set, not a fix to the reported member** — this is the third message on this surface to be fixed one at a time. The three refusals were three hand-written strings of decreasing usefulness:
247
+
248
+ - `unset` — named the variable. Fine. - `absent` — named the header and not the variable. The reported one. - `mismatch` — `inspect: write-credential mismatch`, which named neither, and is the case where knowing WHICH of the two values to look at is the entire remedy. Nobody had reported it, which is not evidence that it was fine.
249
+
250
+ They come from one `inspectWriteHint(refusal, method)` beside the existing read- token hint, so the next arm cannot be added without the vocabulary. The method is folded in because the surface answers for `/erase` and for `/routes` in the same words, and a caller who did not know their call was a mutation is the caller most likely to be reading it.
251
+ - **@voltro/cli** — `ctx.isServer` reaches a LAYOUT loader too, on every server path. It was threaded into the page loader and left off the segment chain, so a layout loader read `undefined` — falsy, i.e. it concluded it was in the browser while server-rendering.
252
+
253
+ Three of the five constructions never passed it: the prerender context in `build.ts`, the dev SSR renderer's layout call, and the test fixture pinning the shape. The two that did are the ones a `tsc` run named, because `SegmentLoaderContext` — the CLI's mirror of `LoaderContext` — had not grown the field at all.
254
+
255
+ Making it REQUIRED rather than optional is what found the other three, and it is the same reasoning the flag itself ships with: an optional `isServer` cannot distinguish "the server forgot to pass it" from "this is the browser", and both spellings of that mistake claim the browser. A field whose whole job is to answer one question must not have a third answer.
256
+
257
+ `webDevSegmentChain.test.ts` asserts the loader argument with an exact `toEqual`, so a field added to one loader's context and not the other fails there. That assertion is the reason this is one release and not two: `tsc` was already green on the test file while the run would have gone red.
258
+ - **@voltro/cli** — The pre-bundled api client is fingerprinted from the DESCRIPTOR SOURCES, so a schema change reaches the browser.
259
+
260
+ Reported: a consumer changed an input schema on a descriptor and `voltro dev` kept serving the old client. The failure is quiet in the worst way — the CLIENT rejects the call, so the api logs nothing, because no request ever arrives.
261
+
262
+ Vite pre-bundles the workspace api client and its optimize-cache hash keys on the lockfile and package.json, never on a pre-bundled dep's source content. So the framework fingerprints the client itself and flips `optimizeDeps.force`. That machinery was right and it was watching the wrong file:
263
+
264
+ **`rpcGroup.generated.ts` imports each descriptor by export name and lifts it. It contains no schemas.** Codegen's own header says so. The generated file is therefore byte-identical across any schema edit, and BOTH mechanisms were structurally blind to it — the across-boot check hashed it, and the in-session watcher watched it.
265
+
266
+ The in-session watcher's own comment already described the symptom ("the browser kept decoding responses against the stale schema"): the cache-busting half was fixed when that was hit, and the DETECTION half kept asking the file that cannot answer. So it never fired. The consumer's third reason — "runs only at boot" — is not quite right, and it does not matter: the in-session mechanism exists and was blind for the same reason. One fingerprint feeds both now.
267
+
268
+ It hashes every `*.query.ts` / `*.mutation.ts` / `*.action.ts` / `*.stream.ts` / `*.event.ts` and every `*.workflow.tsx` descriptor, plus the generated group itself (which is what moves when a procedure is added or removed without a descriptor file changing content). Paths are hashed with contents, so a rename cannot come out as a no-op. `*.server.ts` executors are deliberately excluded — they never reach the browser, and including them would force a re-optimize on every handler edit, which is the whole working day and is how a forced re-optimize gets turned off.
269
+
270
+ **The `proxyTarget` skip is gone from both.** It stood in for "is this api external", and a workspace api served on its own origin has no `proxyTarget` while still being edited locally. `findWorkspaceApiDir` returning a directory is the question that was meant. It survives in exactly one place — the ws proxy, where without a target there is nothing to proxy to — and the test asserts that count rather than its absence.
271
+ - **@voltro/cli** — `voltro probe access` now names the one thing that makes its red meaningless.
272
+
273
+ The command asks "does a declared guard refuse a caller presenting nothing". It turns out that under `voltro dev` a caller presenting nothing is not anonymous: dev resolves a login-less request to a FALLBACK TENANT (`$TENANT ?? 'acme'`). An app whose scopes derive from the tenant therefore admits, and the probe reported `ANSWERED an unauthenticated call` against a guard that is perfectly fine.
274
+
275
+ That is not an occasional false positive, it is a structural one: the local registry only ever holds `voltro dev` / `voltro start` processes — `voltro serve` does not register — so every target the command picks up WITHOUT `--url` is in exactly that state.
276
+
277
+ The failure block now says so, and says what to do instead:
278
+
279
+ voltro probe access --url http://<host>:<port>
280
+
281
+ against a `voltro serve` process, where an anonymous request carries `tenantId: null` — the case a guard actually has to refuse.
282
+
283
+ Found by running the command as a FINDER for the first time rather than as a test: it flagged a shipped template, and the flag was wrong in dev and right about production, for two different reasons. A tool whose red needs a paragraph of context should carry the paragraph.
284
+ - **@voltro/protocol** — A rejected rpc payload no longer answers with the procedure's whole input type.
285
+
286
+ Measured by a consumer against 0.38.0, anonymously, with no session at all:
287
+
288
+ POST /rpc {"tag":"workAreas.create","payload":{"name":"x"}} → { readonly name: string; readonly storeId?: string | null | undefined; readonly type: "department" | "location" | "zone" | "station"; readonly parentId?: string | null | undefined; … } └─ ["type"] └─ is missing
289
+
290
+ That procedure declares `guards: [{ scope: 'workArea:c:o' }]`. The refusal never happened — the payload decode runs first and failed first — so the caller got a field-by-field description of a write they are not allowed to make. On an app with ~700 write procedures that is a free enumeration of the entire write surface for anyone who can reach the port: no session, nothing that looks like rate-limit abuse, and no log line.
291
+
292
+ The rendered TITLE is now the procedure name, and the issue PATH is untouched:
293
+
294
+ workAreas.create input └─ ["type"] └─ is missing
295
+
296
+ So the half that made the 0.37.0 strict-input change cheap to adopt — WHICH key, and whether it is missing or unexpected — survives intact, while the types and the enum members do not. The excess-property case still lists the accepted key NAMES, deliberately: the caller already sent the key, that list is what makes the fix a one-line read, and names without types were not what was reported.
297
+
298
+ **What this does NOT do, stated because the report asked for it.** It does not run `guards:` before the decode. In `@effect/rpc`, a `Request` is decoded against the payload schema and answered on failure without ever reaching `server.write` — so it never reaches the handler and never reaches `applyMiddleware`. Auth middleware runs strictly after the decode, and there is no point in that path holding both a resolved subject and an undecoded payload. Evaluating guards first means replacing the protocol layer, not annotating a schema, and `voltro probe access` therefore still reports a guarded procedure whose input it cannot guess as `inconclusive` rather than `refused`.
299
+
300
+ ### Internal (no consumer-facing effect)
301
+
302
+ - **@voltro/datetime, @voltro/local-first, @voltro/react-native** — `@voltro/datetime`, `@voltro/local-first` and `@voltro/react-native` shipped with no api-extractor golden, so the public-surface drift tripwire did not cover them — and the docs-audit finding that motivated this landed in exactly that gap (the docs promised a `useTimezone()` hook that `@voltro/datetime` never exported, and no gate could see it). All three are wired now, root + subpath entry (`./context`, `./react`, `./schema`): six goldens, `api:check` green on each, and no existing golden changed (the new `paths` entries every sibling map gained are purely additive).
303
+
304
+ Root cause fixed in the generator rather than by hand: `gen-api-extractor.mjs` now creates the package's `etc/` directory with the wiring. api-extractor refuses to create its own report folder, so a package wired without one failed at its first `api:report` instead of at generation — which is how these three went live uncovered. Internal: no consumer-facing behaviour changes.
305
+ - **@voltro/cli** — `gen-api-extractor.mjs --check` verifies the api-surface wiring instead of writing it, and runs in CI (and therefore in `pnpm gate`, which derives its steps from `ci.yml`). It fails when a published entry point has no api-extractor config, no golden, an EMPTY golden, a stale config/golden for a dropped export, or no `api:check` script.
306
+
307
+ It is derived from `publishConfig.exports` inside the generator's own loop — not a curated list and not a second copy of the derivation — so a package that joins the workspace is covered without anyone remembering to add it. It carries a floor (60 packages) for the reason every check in `scripts/` has one: the failure mode of a wiring check is a green line over a walk that found nothing.
308
+
309
+ Verified by injecting each defect and watching it go red (missing golden, empty golden), confirming exit code 1, and confirming `--check` mutates no file. Internal: tooling only.
310
+ - **@voltro/cli** — `rpcSurfaceFingerprint.ts` wrote its composite-key separator as a literal NUL byte instead of ``. Same runtime value, no behaviour change — the file's own 16 tests pass identically before and after.
311
+
312
+ It matters because of what the byte does to the FILE rather than to the hash: a source file containing a NUL is binary to every text tool, so `grep` skips it and prints nothing, which is indistinguishable from a clean file. This repo has been bitten by exactly that — a 1020-line module that every grep-based audit had silently skipped, including one searching for a string that file declares.
313
+
314
+ The guard (`noLiteralNulInSources.test.ts`) caught it on the release gate, in a file added earlier in this same release. The rule was already written down; what enforced it was the test.
315
+
316
+ ---
317
+
42
318
  ## [0.38.0] — 2026-08-14
43
319
 
44
320
  ### ⚠ BREAKING
@@ -5,7 +5,7 @@ property of its respective copyright holders and is used under the terms of
5
5
  its license. This file is provided for attribution; it grants no rights in
6
6
  @voltro/react-native itself, which is proprietary (see LICENSE).
7
7
 
8
- Generated from the resolved runtime dependency closure (5 packages).
8
+ Generated from the resolved runtime dependency closure (6 packages).
9
9
 
10
10
  ---
11
11
 
@@ -37,6 +37,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
37
  SOFTWARE.
38
38
  ```
39
39
 
40
+ ## jose@6.2.8
41
+
42
+ License: MIT
43
+
44
+ ```
45
+ The MIT License (MIT)
46
+
47
+ Copyright (c) 2018 Filip Skokan
48
+
49
+ Permission is hereby granted, free of charge, to any person obtaining a copy
50
+ of this software and associated documentation files (the "Software"), to deal
51
+ in the Software without restriction, including without limitation the rights
52
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
53
+ copies of the Software, and to permit persons to whom the Software is
54
+ furnished to do so, subject to the following conditions:
55
+
56
+ The above copyright notice and this permission notice shall be included in all
57
+ copies or substantial portions of the Software.
58
+
59
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
60
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
61
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
62
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
63
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
64
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
65
+ SOFTWARE.
66
+ ```
67
+
40
68
  ## layerr@3.0.0
41
69
 
42
70
  License: MIT
package/dist/index.d.ts CHANGED
@@ -1,3 +1,69 @@
1
+ import { ApiHandle } from '@voltro/client';
2
+ import { ClientDescriptorMap } from '@voltro/client';
3
+ import { MountedApi } from '@voltro/client';
4
+ import { ResolvableHeaders } from '@voltro/client';
5
+ import { ResolvedClient } from '@voltro/client';
6
+ import { StoreStorageProvider } from '@voltro/client';
7
+ import { SupervisorHandle } from '@voltro/client';
8
+
9
+ /**
10
+ * The async storage this adapter writes through to — `AsyncStorage` from
11
+ * `@react-native-async-storage/async-storage` satisfies it as-is, as does a
12
+ * thin wrapper over `expo-secure-store`.
13
+ *
14
+ * It is a STRUCTURAL type on purpose: this package does not depend on any
15
+ * storage library, so an app can pass whichever one it already has (or a fake,
16
+ * which is how this is tested).
17
+ */
18
+ export declare interface AsyncKeyValueStorage {
19
+ readonly getItem: (key: string) => Promise<string | null>;
20
+ readonly setItem: (key: string, value: string) => Promise<void>;
21
+ readonly removeItem: (key: string) => Promise<void>;
22
+ /** Optional: used by `hydrate()` when no explicit key list is given. */
23
+ readonly getAllKeys?: () => Promise<ReadonlyArray<string>>;
24
+ /** Optional: a batched read, used when available. */
25
+ readonly multiGet?: (keys: ReadonlyArray<string>) => Promise<ReadonlyArray<readonly [string, string | null]>>;
26
+ }
27
+
28
+ export declare interface AsyncStoragePersistence {
29
+ /**
30
+ * Load the persisted keys into memory. Await this BEFORE rendering; install
31
+ * the provider afterwards.
32
+ *
33
+ * Idempotent: a second call re-reads, which is what a "reload from disk"
34
+ * would need. Safe to call concurrently — the in-flight promise is shared.
35
+ */
36
+ readonly hydrate: () => Promise<void>;
37
+ /** True once `hydrate()` has completed at least once. */
38
+ readonly hydrated: () => boolean;
39
+ /** Install this with `setStoreStorage()` from `@voltro/client`. */
40
+ readonly provider: StoreStorageProvider;
41
+ /**
42
+ * Resolve when every queued write has settled. For tests, and for an app that
43
+ * wants to flush before backgrounding — not required for correctness, since
44
+ * writes are queued per key and the last one wins.
45
+ */
46
+ readonly flush: () => Promise<void>;
47
+ /** Keys currently held in memory. Diagnostics; not a stable ordering. */
48
+ readonly keys: () => ReadonlyArray<string>;
49
+ }
50
+
51
+ export declare interface AsyncStoragePersistenceOptions {
52
+ readonly storage: AsyncKeyValueStorage;
53
+ /**
54
+ * Which keys to hydrate. Give this when your storage holds more than Voltro's
55
+ * stores — hydrating a device's entire key space to serve four store keys is
56
+ * a slow boot for no benefit.
57
+ *
58
+ * Omitted, the adapter asks `getAllKeys()`; if the storage has no
59
+ * `getAllKeys`, omitting this is an ERROR at `hydrate()` rather than a silent
60
+ * empty hydration, because an empty hydration looks exactly like a first run.
61
+ */
62
+ readonly keys?: ReadonlyArray<string>;
63
+ /** Called when a write-through fails. Default: `console.warn`. */
64
+ readonly onError?: (key: string, error: unknown) => void;
65
+ }
66
+
1
67
  export declare type BackgroundSyncAction = {
2
68
  readonly type: 'foreground';
3
69
  } | {
@@ -36,6 +102,25 @@ export declare interface BackgroundSyncState {
36
102
 
37
103
  export declare type BackgroundSyncStatus = 'idle' | 'syncing' | 'success' | 'error';
38
104
 
105
+ /** The browser's `navigator.onLine` + its events. The default, and the reason
106
+ * the same screen still behaves under jsdom or in a web preview. */
107
+ export declare const browserOnlineSource: OnlineSource;
108
+
109
+ /**
110
+ * Build a React-Native persistence adapter over an async key-value storage.
111
+ *
112
+ * ```ts
113
+ * import AsyncStorage from '@react-native-async-storage/async-storage'
114
+ * import { setStoreStorage } from '@voltro/client'
115
+ * import { createAsyncStoragePersistence } from '@voltro/react-native'
116
+ *
117
+ * const persistence = createAsyncStoragePersistence({ storage: AsyncStorage })
118
+ * await persistence.hydrate() // BEFORE the first render
119
+ * setStoreStorage(persistence.provider)
120
+ * ```
121
+ */
122
+ export declare const createAsyncStoragePersistence: (options: AsyncStoragePersistenceOptions) => AsyncStoragePersistence;
123
+
39
124
  /**
40
125
  * The descriptor a `*.deepLink.ts` file default-exports. `_tag` marks it for
41
126
  * the (future) discovery walk without relying on structural guessing.
@@ -63,6 +148,11 @@ export declare type DeepLinkParams<Pattern extends string> = Pattern extends `${
63
148
  readonly [K in Param]: string;
64
149
  } : Record<string, never>;
65
150
 
151
+ /** The default constructor: React Native's global `WebSocket`. Exported so the
152
+ * refusal below is testable — an untestable error message is one nobody has
153
+ * ever read. */
154
+ export declare const defaultWebSocketConstructor: (url: string, protocols?: string | ReadonlyArray<string>) => WebSocket;
155
+
66
156
  /**
67
157
  * Declare a deep link.
68
158
  *
@@ -149,6 +239,24 @@ export declare const DEVICES_TABLE = "_voltro_devices";
149
239
  */
150
240
  export declare type DeviceUpsert<Result = unknown> = (registration: DeviceRegistration) => Promise<Result>;
151
241
 
242
+ /**
243
+ * Match `path` against the table and RUN the winning handler. Returns the
244
+ * captured params, or `null` when nothing matched.
245
+ *
246
+ * This exists because `matchFirstDeepLink` alone is not usable for the thing it
247
+ * is for. Its descriptors come from a HETEROGENEOUS array, so `Pattern` erases
248
+ * to `string`, and `DeepLinkParams<string>` is `Record<string, never>` — the
249
+ * handler it hands back rejects the params it hands back with it. Every caller
250
+ * had to cast, and the template's did not, which nothing noticed because no
251
+ * harness typechecked the template.
252
+ *
253
+ * The erasure happens ONCE, here, where it is defensible: at runtime a matched
254
+ * pattern's params ARE `Record<string, string>`, and the per-pattern type is a
255
+ * derivation of a literal the caller no longer has. `runDeepLink` keeps the
256
+ * fully-typed single-descriptor path for a caller that does.
257
+ */
258
+ export declare const dispatchDeepLink: (descriptors: ReadonlyArray<DeepLinkDescriptor>, path: string) => Record<string, string> | null;
259
+
152
260
  /**
153
261
  * Subscribe to "app returned to the foreground". Returns an unsubscribe.
154
262
  *
@@ -190,6 +298,19 @@ export declare const matchFirstDeepLink: (descriptors: ReadonlyArray<DeepLinkDes
190
298
  readonly params: Record<string, string>;
191
299
  } | null;
192
300
 
301
+ /** One api this app talks to. `group` and `descriptors` come from the api's
302
+ * generated rpc surface — on mobile, from the file `voltro codegen` writes
303
+ * into the app (`.framework/mobileApis.generated.ts`). */
304
+ export declare interface MobileApiBinding {
305
+ readonly name: string;
306
+ readonly group: MountedApi['group'];
307
+ readonly descriptors: ClientDescriptorMap;
308
+ /** `ws(s)://host:port/ws`. On a device this is NOT localhost — see
309
+ * {@link resolveDevWsUrl}. */
310
+ readonly wsUrl: string;
311
+ readonly headers?: ResolvableHeaders | undefined;
312
+ }
313
+
193
314
  export declare interface MobileConnectionControls {
194
315
  /** Report that a call failed — bumps `failureCount`, flips to `degraded`. */
195
316
  readonly reportFailure: () => void;
@@ -199,7 +320,7 @@ export declare interface MobileConnectionControls {
199
320
 
200
321
  export declare interface MobileConnectionState {
201
322
  readonly status: MobileConnectionStatus;
202
- /** `navigator.onLine` (true when unknowable, e.g. SSR / headless RN). */
323
+ /** Reachability as reported by the configured {@link OnlineSource}. */
203
324
  readonly online: boolean;
204
325
  /** Consecutive reported failures with no success since. 0 when healthy. */
205
326
  readonly failureCount: number;
@@ -208,6 +329,37 @@ export declare interface MobileConnectionState {
208
329
 
209
330
  export declare type MobileConnectionStatus = 'connected' | 'degraded' | 'offline';
210
331
 
332
+ /** The subset of the NetInfo module used. `fetch()` seeds the first value,
333
+ * `addEventListener` reports changes and returns an unsubscribe. */
334
+ export declare interface NetInfoLike {
335
+ readonly addEventListener: (listener: (state: NetInfoState) => void) => () => void;
336
+ readonly fetch?: () => Promise<NetInfoState>;
337
+ }
338
+
339
+ /**
340
+ * Reachability from `@react-native-community/netinfo` (or Expo's re-export).
341
+ *
342
+ * ```ts
343
+ * import NetInfo from '@react-native-community/netinfo'
344
+ * const status = useMobileConnectionStatus({ onlineSource: netInfoOnlineSource(NetInfo) })
345
+ * ```
346
+ *
347
+ * `isInternetReachable` is only believed when it is a BOOLEAN. NetInfo reports
348
+ * `null` while its reachability probe is still outstanding, and treating that
349
+ * as `false` makes an app flash "offline" for a moment on every cold start and
350
+ * on every network change — so a `null` falls back to `isConnected`, which is
351
+ * the link-layer answer and is available immediately.
352
+ */
353
+ export declare const netInfoOnlineSource: (netInfo: NetInfoLike) => OnlineSource;
354
+
355
+ /** The shape of `@react-native-community/netinfo`'s state that matters here.
356
+ * Structural, so this package depends on no native module. */
357
+ export declare interface NetInfoState {
358
+ readonly isConnected: boolean | null;
359
+ /** `null` while the probe is still out — see the treatment below. */
360
+ readonly isInternetReachable?: boolean | null;
361
+ }
362
+
211
363
  /**
212
364
  * The mobile client posture. Spread into the client config on RN:
213
365
  *
@@ -232,6 +384,19 @@ export declare interface OfflineFirstDefaults {
232
384
 
233
385
  export declare const offlineFirstDefaults: OfflineFirstDefaults;
234
386
 
387
+ /**
388
+ * A source of reachability. `subscribe` reports every change and returns an
389
+ * unsubscribe; `read` gives the value to start from.
390
+ *
391
+ * Injected rather than detected, because detection is exactly what went wrong:
392
+ * a `typeof navigator === 'undefined' ? true : …` fallback answers "online" on
393
+ * every platform that does not implement the API it is testing for.
394
+ */
395
+ export declare interface OnlineSource {
396
+ readonly read: () => boolean;
397
+ readonly subscribe: (onChange: (online: boolean) => void) => () => void;
398
+ }
399
+
235
400
  /**
236
401
  * Register (or re-register, on token rotation) the current device.
237
402
  *
@@ -259,6 +424,21 @@ export declare const registerDevice: <Result = unknown>(upsert: DeviceUpsert<Res
259
424
  */
260
425
  export declare const resolveDeviceRegistration: (input: DeviceRegistrationInput, env?: DeviceRegistrationEnv) => DeviceRegistration;
261
426
 
427
+ /**
428
+ * Turn a dev-machine host into a ws URL a DEVICE can reach.
429
+ *
430
+ * The trap this exists for: `localhost` on a phone is the PHONE. An app pointed
431
+ * at `ws://localhost:4000/ws` in development connects to nothing, times out,
432
+ * and retries forever — which reads as a broken framework rather than a wrong
433
+ * host. Expo already knows the LAN address of the machine running Metro
434
+ * (`expo-constants`' `hostUri`, e.g. `192.168.1.20:8081`), so pass that in and
435
+ * this swaps in the api's port.
436
+ *
437
+ * A simulator is the exception — it shares the host's loopback — but using the
438
+ * LAN address works there too, so there is no branch to get wrong.
439
+ */
440
+ export declare const resolveDevWsUrl: (hostUri: string | undefined, port: number, path?: string) => string;
441
+
262
442
  /**
263
443
  * Match `path` against a descriptor and, on a hit, invoke its handler with the
264
444
  * captured params. Returns the params (so callers know it matched) or `null`.
@@ -287,6 +467,52 @@ export declare interface ShouldSyncOptions {
287
467
  readonly enabled: boolean;
288
468
  }
289
469
 
470
+ /**
471
+ * Connect every api and keep them connected.
472
+ *
473
+ * ```ts
474
+ * const supervisor = startMobileApis({
475
+ * apis: mobileApis(wsUrl),
476
+ * onChange: (clients, initialized) => setState({ clients, initialized }),
477
+ * })
478
+ * // on unmount:
479
+ * supervisor.dispose()
480
+ * ```
481
+ *
482
+ * `reconnect()` on the returned handle forces a fresh socket for every api —
483
+ * call it after a sign-in or a tenant switch so the connection re-resolves who
484
+ * it is. The supervisor blanks caches across that swap on purpose: the next
485
+ * subject may be entitled to less than the previous one.
486
+ */
487
+ export declare const startMobileApis: (options: StartMobileApisOptions) => SupervisorHandle;
488
+
489
+ export declare interface StartMobileApisOptions {
490
+ readonly apis: ReadonlyArray<MobileApiBinding>;
491
+ /** Called whenever the live client set changes: initial connect, a reconnect
492
+ * swap, teardown. Mirror it into state and render once `initialized`. */
493
+ readonly onChange: (clients: ReadonlyMap<string, ResolvedClient>, initialized: boolean) => void;
494
+ /**
495
+ * How to construct a WebSocket. Defaults to the global one React Native
496
+ * provides. Injected so this module can be tested without a socket — and so
497
+ * an app on a runtime with a different WebSocket can say so.
498
+ */
499
+ readonly webSocketConstructor?: (url: string, protocols?: string | ReadonlyArray<string>) => WebSocket;
500
+ /** Override the retry schedule (default: 500ms doubling, capped at 5s). */
501
+ readonly retryDelayMs?: (attempt: number) => number;
502
+ }
503
+
504
+ /**
505
+ * Turn the supervisor's live client set into the `apis` map the client provider
506
+ * takes.
507
+ *
508
+ * This lives in the package rather than in the template because it is where the
509
+ * two halves meet — the BINDING (name, descriptors, url) and the live
510
+ * connection — and a template copy would be an untested one. An api that has not
511
+ * connected yet is simply absent from the map; the hooks render their loading
512
+ * state, which is the honest answer while a phone is on a train.
513
+ */
514
+ export declare const toApiHandles: (apis: ReadonlyArray<MobileApiBinding>, clients: ReadonlyMap<string, ResolvedClient>) => ReadonlyMap<string, ApiHandle>;
515
+
290
516
  /**
291
517
  * Register a periodic + foreground-triggered sync callback.
292
518
  *
@@ -322,6 +548,8 @@ export declare interface UseBackgroundSyncResult extends BackgroundSyncState {
322
548
  readonly sync: () => void;
323
549
  }
324
550
 
551
+ export declare const useMobileConnectionStatus: (options?: UseMobileConnectionStatusOptions) => MobileConnectionState & MobileConnectionControls;
552
+
325
553
  /**
326
554
  * Observe mobile connection health.
327
555
  *
@@ -330,12 +558,32 @@ export declare interface UseBackgroundSyncResult extends BackgroundSyncState {
330
558
  * {status !== 'connected' && <OfflineBanner status={status} />}
331
559
  * ```
332
560
  *
333
- * Standalone by design (see the file header): it derives `offline` from
334
- * `navigator.onLine` + its events, and `degraded` from failures the app reports
335
- * it does not reach into any transport. Coming back online clears the failure
561
+ * Standalone by design (see the file header): it derives `offline` from the
562
+ * injected {@link OnlineSource}, and `degraded` from failures the app reports
563
+ * it does not reach into any transport. Coming back online clears the failure
336
564
  * count, on the same reasoning as the web hook: those failures were the offline
337
565
  * window itself.
338
566
  */
339
- export declare const useMobileConnectionStatus: () => MobileConnectionState & MobileConnectionControls;
567
+ export declare interface UseMobileConnectionStatusOptions {
568
+ /** Where "online" comes from. Defaults to the browser source; pass
569
+ * `netInfoOnlineSource(NetInfo)` on a device. */
570
+ readonly onlineSource?: OnlineSource;
571
+ }
572
+
573
+ /**
574
+ * Wrap a WebSocket constructor so the supervisor hears what the socket does.
575
+ *
576
+ * Exported because it is the ONE piece of this module that can be tested
577
+ * without a device: the socket itself is constructed lazily, deep inside the
578
+ * Effect socket layer, when the client first connects — so a test that asserts
579
+ * "a socket was created" asserts nothing until there is a real connection to
580
+ * make. What CAN be pinned here is that a socket, once created, reports open,
581
+ * close and error onward. Without those three the retry loop is never told
582
+ * anything and a dropped connection stays dropped, silently, forever.
583
+ *
584
+ * RN needs no connect-timeout shim (web has one): a failed connect on a device
585
+ * fires `error` and then `close`.
586
+ */
587
+ export declare const wireSocket: (construct: (url: string, protocols?: string | ReadonlyArray<string>) => WebSocket, onOpen: () => void, onIssue: (kind: "close" | "error" | "connect-timeout") => void) => (url: string, protocols?: string | ReadonlyArray<string>) => WebSocket;
340
588
 
341
589
  export { }
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { a as e, i as t, n, r, t as i } from "./devices-BjXAU-8I.js";
2
2
  import { useCallback as a, useEffect as o, useReducer as s, useRef as c, useState as l } from "react";
3
+ import { buildApiRuntime as u, startApiSupervisor as d } from "@voltro/client";
3
4
  //#region src/deepLink.ts
4
- var u = (e) => {
5
+ var f = (e) => {
5
6
  let t = e.pattern;
6
7
  if (t.length === 0 || t[0] !== "/") throw Error(`defineDeepLink: pattern must start with "/" (got "${t}")`);
7
8
  return {
@@ -9,7 +10,7 @@ var u = (e) => {
9
10
  pattern: t,
10
11
  handler: e.handler
11
12
  };
12
- }, d = (e) => {
13
+ }, p = (e) => {
13
14
  let t = e, n = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\//.exec(t);
14
15
  if (n) {
15
16
  let e = t.slice(n[0].length), r = n[1].toLowerCase();
@@ -26,8 +27,8 @@ var u = (e) => {
26
27
  return e;
27
28
  }
28
29
  });
29
- }, f = (e, t) => {
30
- let n = d(e), r = d(t);
30
+ }, m = (e, t) => {
31
+ let n = p(e), r = p(t);
31
32
  if (n.length !== r.length) return null;
32
33
  let i = {};
33
34
  for (let e = 0; e < n.length; e++) {
@@ -39,19 +40,24 @@ var u = (e) => {
39
40
  } else if (t !== "*" && t !== a) return null;
40
41
  }
41
42
  return i;
42
- }, p = (e, t) => {
43
- let n = f(e.pattern, t);
43
+ }, h = (e, t) => {
44
+ let n = m(e.pattern, t);
44
45
  return n === null ? null : (e.handler(n), n);
45
- }, m = (e, t) => {
46
+ }, g = (e, t) => {
46
47
  for (let n of e) {
47
- let e = f(n.pattern, t);
48
+ let e = m(n.pattern, t);
48
49
  if (e !== null) return {
49
50
  descriptor: n,
50
51
  params: e
51
52
  };
52
53
  }
53
54
  return null;
54
- }, h = {
55
+ }, _ = (e, t) => {
56
+ let n = g(e, t);
57
+ if (n === null) return null;
58
+ let r = n.descriptor.handler;
59
+ return r(n.params), n.params;
60
+ }, v = {
55
61
  status: "idle",
56
62
  isForeground: !0,
57
63
  lastSyncAt: void 0,
@@ -59,7 +65,7 @@ var u = (e) => {
59
65
  lastError: void 0,
60
66
  successCount: 0,
61
67
  failureCount: 0
62
- }, g = (e, t) => {
68
+ }, y = (e, t) => {
63
69
  switch (t.type) {
64
70
  case "foreground": return e.isForeground ? e : {
65
71
  ...e,
@@ -90,11 +96,11 @@ var u = (e) => {
90
96
  failureCount: e.failureCount + 1
91
97
  };
92
98
  case "reset": return {
93
- ...h,
99
+ ...v,
94
100
  isForeground: e.isForeground
95
101
  };
96
102
  }
97
- }, _ = (e, t, n, r = !1) => !(!n.enabled || e.status === "syncing" || !r && !e.isForeground || !r && n.intervalMs > 0 && e.lastAttemptAt !== void 0 && t - e.lastAttemptAt < n.intervalMs), v = (e, t) => {
103
+ }, b = (e, t, n, r = !1) => !(!n.enabled || e.status === "syncing" || !r && !e.isForeground || !r && n.intervalMs > 0 && e.lastAttemptAt !== void 0 && t - e.lastAttemptAt < n.intervalMs), x = (e, t) => {
98
104
  if (typeof document > "u" || typeof window > "u") return () => {};
99
105
  let n = () => {
100
106
  document.visibilityState === "visible" ? e() : t();
@@ -102,25 +108,25 @@ var u = (e) => {
102
108
  return document.addEventListener("visibilitychange", n), window.addEventListener("focus", e), () => {
103
109
  document.removeEventListener("visibilitychange", n), window.removeEventListener("focus", e);
104
110
  };
105
- }, y = 5 * 6e4, b = (e, t = {}) => {
106
- let n = t.intervalMs ?? y, r = t.syncOnForeground ?? !0, i = t.enabled ?? !0, l = t.now ?? Date.now, u = t.subscribeForeground ?? v, [d, f] = s(g, h), p = c(e);
111
+ }, S = 3e5, C = (e, t = {}) => {
112
+ let n = t.intervalMs ?? S, r = t.syncOnForeground ?? !0, i = t.enabled ?? !0, l = t.now ?? Date.now, u = t.subscribeForeground ?? x, [d, f] = s(y, v), p = c(e);
107
113
  p.current = e;
108
114
  let m = c(d);
109
115
  m.current = d;
110
- let b = c(!0), x = a((e) => {
111
- _(m.current, l(), {
116
+ let h = c(!0), g = a((e) => {
117
+ b(m.current, l(), {
112
118
  intervalMs: n,
113
119
  enabled: i
114
120
  }, e) && (f({
115
121
  type: "syncStarted",
116
122
  at: l()
117
123
  }), Promise.resolve().then(() => p.current()).then(() => {
118
- b.current && f({
124
+ h.current && f({
119
125
  type: "syncSucceeded",
120
126
  at: l()
121
127
  });
122
128
  }).catch((e) => {
123
- b.current && f({
129
+ h.current && f({
124
130
  type: "syncFailed",
125
131
  at: l(),
126
132
  error: e instanceof Error ? e.message : String(e)
@@ -131,33 +137,33 @@ var u = (e) => {
131
137
  n,
132
138
  l
133
139
  ]);
134
- o(() => (b.current = !0, () => {
135
- b.current = !1;
140
+ o(() => (h.current = !0, () => {
141
+ h.current = !1;
136
142
  }), []), o(() => u(() => {
137
- f({ type: "foreground" }), r && x(!0);
143
+ f({ type: "foreground" }), r && g(!0);
138
144
  }, () => f({ type: "background" })), [
139
145
  u,
140
146
  r,
141
- x
147
+ g
142
148
  ]), o(() => {
143
149
  if (!i || n <= 0) return;
144
- let e = setInterval(() => x(!1), n);
150
+ let e = setInterval(() => g(!1), n);
145
151
  return () => clearInterval(e);
146
152
  }, [
147
153
  i,
148
154
  n,
149
- x
155
+ g
150
156
  ]);
151
- let S = a(() => x(!0), [x]);
157
+ let _ = a(() => g(!0), [g]);
152
158
  return {
153
159
  ...d,
154
- sync: S
160
+ sync: _
155
161
  };
156
- }, x = {
162
+ }, w = {
157
163
  localFirst: !0,
158
164
  optimistic: !0,
159
165
  syncOnForeground: !0,
160
- syncIntervalMs: 5 * 6e4,
166
+ syncIntervalMs: 3e5,
161
167
  showSyncStatus: !0,
162
168
  retryBackoffMs: [
163
169
  1e3,
@@ -165,32 +171,151 @@ var u = (e) => {
165
171
  15e3,
166
172
  6e4
167
173
  ]
168
- }, S = (e, t) => e ? t > 0 ? "degraded" : "connected" : "offline", C = () => typeof navigator > "u" || navigator.onLine, w = () => {
169
- let [e, t] = l(C), [n, r] = l(0), [i, s] = l(void 0), u = c(!0);
170
- o(() => (u.current = !0, () => {
171
- u.current = !1;
172
- }), []), o(() => {
173
- if (typeof window > "u") return;
174
- let e = () => {
175
- t(!0), r(0);
176
- }, n = () => t(!1);
177
- return window.addEventListener("online", e), window.addEventListener("offline", n), () => {
178
- window.removeEventListener("online", e), window.removeEventListener("offline", n);
174
+ }, T = (e, t) => e ? t > 0 ? "degraded" : "connected" : "offline", E = {
175
+ read: () => typeof navigator > "u" || navigator.onLine,
176
+ subscribe: (e) => {
177
+ if (typeof window > "u") return () => {};
178
+ let t = () => e(!0), n = () => e(!1);
179
+ return window.addEventListener("online", t), window.addEventListener("offline", n), () => {
180
+ window.removeEventListener("online", t), window.removeEventListener("offline", n);
179
181
  };
180
- }, []);
181
- let d = a(() => {
182
- u.current && (r((e) => e + 1), s(Date.now()));
183
- }, []), f = a(() => {
184
- u.current && r(0);
182
+ }
183
+ }, D = (e) => {
184
+ let t = (e) => typeof e.isInternetReachable == "boolean" ? e.isInternetReachable : e.isConnected === !0, n = !0;
185
+ return {
186
+ read: () => n,
187
+ subscribe: (r) => {
188
+ let i = e.addEventListener((e) => {
189
+ n = t(e), r(n);
190
+ });
191
+ return e.fetch?.().then((e) => {
192
+ n = t(e), r(n);
193
+ }).catch(() => {}), i;
194
+ }
195
+ };
196
+ }, O = (e) => {
197
+ let t = e?.onlineSource ?? E, [n, r] = l(() => t.read()), [i, s] = l(0), [u, d] = l(void 0), f = c(!0);
198
+ o(() => (f.current = !0, () => {
199
+ f.current = !1;
200
+ }), []), o(() => t.subscribe((e) => {
201
+ r(e), e && s(0);
202
+ }), [t]);
203
+ let p = a(() => {
204
+ f.current && (s((e) => e + 1), d(Date.now()));
205
+ }, []), m = a(() => {
206
+ f.current && s(0);
185
207
  }, []);
186
208
  return {
187
- status: S(e, n),
188
- online: e,
189
- failureCount: n,
190
- lastFailureAt: i,
191
- reportFailure: d,
192
- reportSuccess: f
209
+ status: T(n, i),
210
+ online: n,
211
+ failureCount: i,
212
+ lastFailureAt: u,
213
+ reportFailure: p,
214
+ reportSuccess: m
193
215
  };
216
+ }, k = (e) => {
217
+ let { storage: t, keys: n } = e, r = e.onError ?? ((e, t) => {
218
+ console.warn(`[voltro] persisting '${e}' failed`, t);
219
+ }), i = /* @__PURE__ */ new Map(), a = !1, o = null, s = /* @__PURE__ */ new Map(), c = null, l = async () => {
220
+ for (; s.size > 0;) {
221
+ let [e, n] = s.entries().next().value;
222
+ s.delete(e);
223
+ try {
224
+ n === null ? await t.removeItem(e) : await t.setItem(e, n);
225
+ } catch (t) {
226
+ r(e, t);
227
+ }
228
+ }
229
+ }, u = () => {
230
+ c === null && (c = Promise.resolve().then(l).finally(() => {
231
+ c = null;
232
+ }));
233
+ }, d = async (e) => {
234
+ if (e.length === 0) return;
235
+ if (t.multiGet) {
236
+ let n = await t.multiGet(e);
237
+ for (let [e, t] of n) t === null ? i.delete(e) : i.set(e, t);
238
+ return;
239
+ }
240
+ let n = await Promise.all(e.map((e) => t.getItem(e)));
241
+ e.forEach((e, t) => {
242
+ let r = n[t];
243
+ r == null ? i.delete(e) : i.set(e, r);
244
+ });
245
+ }, f = () => {
246
+ if (o !== null) return o;
247
+ let e = (async () => {
248
+ let e;
249
+ if (n !== void 0) e = n;
250
+ else if (t.getAllKeys) e = await t.getAllKeys();
251
+ else throw Error("createAsyncStoragePersistence: the storage has no getAllKeys(), so the keys to hydrate cannot be discovered. Pass an explicit `keys: [...]` listing the persisted stores' keys.");
252
+ await d(e), a = !0;
253
+ })();
254
+ return o = e, e.finally(() => {
255
+ o = null;
256
+ });
257
+ }, p = {
258
+ getItem: (e) => i.get(e) ?? null,
259
+ setItem: (e, t) => {
260
+ i.set(e, t), s.set(e, t), u();
261
+ },
262
+ removeItem: (e) => {
263
+ i.delete(e), s.set(e, null), u();
264
+ }
265
+ };
266
+ return {
267
+ hydrate: f,
268
+ hydrated: () => a,
269
+ provider: () => p,
270
+ flush: async () => {
271
+ for (; c !== null || s.size > 0;) await (c ?? Promise.resolve()), c === null && s.size > 0 && u();
272
+ },
273
+ keys: () => [...i.keys()]
274
+ };
275
+ }, A = (e, t) => {
276
+ let n = globalThis.WebSocket;
277
+ if (n === void 0) throw Error("startMobileApis: no global WebSocket. React Native provides one; if you are running these bindings somewhere else, pass `webSocketConstructor`.");
278
+ return t === void 0 ? new n(e) : new n(e, t);
279
+ }, j = (e, t, n) => (r, i) => {
280
+ let a = e(r, i);
281
+ return a.addEventListener("open", () => t()), a.addEventListener("close", () => n("close")), a.addEventListener("error", () => n("error")), a;
282
+ }, M = (e) => {
283
+ let t = e.webSocketConstructor ?? A;
284
+ return d({
285
+ apis: e.apis.map((e) => ({
286
+ name: e.name,
287
+ group: e.group,
288
+ descriptors: e.descriptors,
289
+ wsUrl: e.wsUrl,
290
+ ...e.headers === void 0 ? {} : { headers: e.headers }
291
+ })),
292
+ ...e.retryDelayMs === void 0 ? {} : { retryDelayMs: e.retryDelayMs },
293
+ onChange: e.onChange,
294
+ buildClient: async (e, n, r, i) => await u({
295
+ name: e.name,
296
+ wsUrl: e.wsUrl,
297
+ group: e.group,
298
+ ...e.headers === void 0 ? {} : { headers: e.headers },
299
+ webSocketConstructor: j(t, r, i)
300
+ })
301
+ });
302
+ }, N = (e, t, n = "/ws") => {
303
+ let r = (e ?? "").split(":")[0];
304
+ return r === void 0 || r === "" || r === "localhost" || r === "127.0.0.1" ? `ws://localhost:${t}${n}` : `ws://${r}:${t}${n}`;
305
+ }, P = (e, t) => {
306
+ let n = /* @__PURE__ */ new Map();
307
+ for (let r of e) {
308
+ let e = t.get(r.name);
309
+ e !== void 0 && n.set(r.name, {
310
+ runtime: e.runtime,
311
+ cache: e.cache,
312
+ client: e.client,
313
+ descriptors: r.descriptors,
314
+ inspectBaseUrl: r.wsUrl.replace(/^ws/, "http").replace(/\/ws$/, ""),
315
+ errorBus: e.errorBus
316
+ });
317
+ }
318
+ return n;
194
319
  };
195
320
  //#endregion
196
- export { i as DEVICES_TABLE, n as DEVICE_PLATFORMS, g as backgroundSyncReducer, u as defineDeepLink, S as deriveConnectionStatus, h as initialBackgroundSyncState, r as isDevicePlatform, f as matchDeepLink, m as matchFirstDeepLink, x as offlineFirstDefaults, t as registerDevice, e as resolveDeviceRegistration, p as runDeepLink, _ as shouldSync, b as useBackgroundSync, w as useMobileConnectionStatus };
321
+ export { i as DEVICES_TABLE, n as DEVICE_PLATFORMS, y as backgroundSyncReducer, E as browserOnlineSource, k as createAsyncStoragePersistence, A as defaultWebSocketConstructor, f as defineDeepLink, T as deriveConnectionStatus, _ as dispatchDeepLink, v as initialBackgroundSyncState, r as isDevicePlatform, m as matchDeepLink, g as matchFirstDeepLink, D as netInfoOnlineSource, w as offlineFirstDefaults, t as registerDevice, N as resolveDevWsUrl, e as resolveDeviceRegistration, h as runDeepLink, b as shouldSync, M as startMobileApis, P as toApiHandles, C as useBackgroundSync, O as useMobileConnectionStatus, j as wireSocket };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/react-native",
3
- "version": "0.38.0",
3
+ "version": "0.39.1",
4
4
  "description": "React Native bindings for the framework: device-registration primitive, background-sync state machine, offline-first client defaults + connection-status surface, and the deep-link declaration shape — the credential-free mobile plumbing on top of the RN-safe React client.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -38,7 +38,8 @@
38
38
  "node": ">=24.0.0"
39
39
  },
40
40
  "dependencies": {
41
- "@voltro/database": "0.38.0"
41
+ "@voltro/client": "0.39.1",
42
+ "@voltro/database": "0.39.1"
42
43
  },
43
44
  "peerDependencies": {
44
45
  "react": "^19.0.0"