@voltro/client 0.39.1 → 0.41.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/CHANGELOG.md CHANGED
@@ -39,6 +39,238 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.41.0] — 2026-08-17
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/web, @voltro/cli** — `middleware.ts` exports `defineMiddleware(...)` (from `@voltro/web/middleware`) instead of a bare function, and each export carries its own `match`. Several middlewares per file are allowed; **at most one may match a given route**.
47
+
48
+ Migration: the codemod wraps the existing default export. That is behaviour-preserving — no `match` means every server-rendered route, which is what an unwrapped middleware did — and its note explains how to replace a hand-written path gate with a `match`.
49
+
50
+ **Why it was worth a break.** A hand-written `if (!req.pathname.startsWith('/app')) return` is invisible: nothing can tell you a middleware runs nowhere, or that two of them claim one route. `match` puts it where both the boot and `voltro doctor` can read it.
51
+
52
+ **The matcher speaks ROUTES, not URL patterns** — `under` / `routes` / `except`, validated against the app's own route patterns. A path matching no route refuses the boot instead of silently never firing. This is the deliberate difference from the `'/((?!api|_next/static|…).*)'` shape: our hook runs after route matching, so an app has never needed to know its own asset layout, and non-page requests are reachable only by asking (`assets: true`) — where, note, there is no render, so only `setCookies` takes effect.
53
+
54
+ An overlap refuses the boot and names both middlewares plus the route. Declaration order is not a semantic, "most specific wins" silently drops the broader hook, and merging needs a per-field rule nobody remembers — so two hooks writing one `authorization` header is a refusal, not a resolution.
55
+
56
+ **The web bundle budget moved UP, and the split is worth stating** because only one half is a cost the framework imposes:
57
+
58
+ | measured | before | after | | --- | --- | --- | | first load | 184 955 B | 185 309 B (**+354**) | | lazy route chunks | 3 502 B | 4 415 B (+913) |
59
+
60
+ The **+354 B of first load is the real price** — one `serverContext` chunk, 0.2 KB gz, which every app now carries whether or not it declares a middleware. That is the number to argue with, and it leaves 6.7 KB of headroom under the ceiling.
61
+
62
+ The +913 B is NOT a per-route regression: the fixture gained four routes (`exact`, `exact/[id]`, `mw`, `mw/skip`) to exercise the feature end to end, at 0.1–0.2 KB gz each, which accounts for the growth without remainder. Re-pinned with `--update` rather than by hand, so the `slackFloor` keeps ratcheting — a ceiling nobody lowers again silently permits re-inflating to the old number.
63
+
64
+ ### Fixed
65
+
66
+ - **@voltro/data-transfer, @voltro/cli** — `voltro data export` could not export a table whose primary key is not named `id`, and one of its two failure modes reported success.
67
+
68
+ The keyset column was `columns.find(c => c.type === 'id')?.name ?? 'id'`, and `type: 'id'` is tagged only on a column that is BOTH the single-column primary key AND literally named `id` — identically in all four dialect introspectors. So any introspected table with another PK name was ordered by a column that does not exist. It now comes from the real primary key (the synthesised `<table>_pkey` index), with the declared `id()` column still winning where there is one.
69
+
70
+ **A composite or absent primary key is now REFUSED**, not silently ordered by the first column: keyset pagination on a non-unique order splits equal values across page boundaries, so rows are dropped or duplicated into a bundle that reports success. Bounded exports are recoverable; a quietly short backup is discovered at the restore.
71
+
72
+ **A requested table missing from the schema is refused too.** `scope: { kind: 'tables' }` used to drop unknown names, so a run that explicitly named a table wrote `"tables": []` and printed `export complete` with exit 0. `kind: 'all'` over an empty database is still a legal empty export — the asymmetry is deliberate: a named table is an expectation.
73
+
74
+ **Failure reasons survive.** `String(e?.message ?? e)` produced `"write table failed: "` with nothing after the colon — `??` falls back on null/undefined, and an Effect `TaggedError` carries an empty-string `message`. Every catch site in the exporter now reports tag, message or cause.
75
+
76
+ **New: `voltro data export --exclude a,b`** — everything except these, resolved against the live table list. It is the escape hatch the refusals above require; without it a single unkeyable table would block a whole-database export. An unknown name is refused for the same reason. Direct target only (the expansion needs the live table list), and it expands to an explicit `tables` scope, so the manifest records what was actually exported.
77
+
78
+ Reported with a reduced repro, a four-way variation over PK TYPES that ruled type out, and two disproved hypotheses. The affected tables include `@effect/cluster`'s own (`cluster_locks`, `cluster_migrations`), so no app running workflows could take a whole-database export.
79
+ - **@voltro/database, @voltro/runtime, @voltro/cli** — `.encrypted()` had three writers and two encodings. The store wrote `encrypt(JSON.stringify(v))`; `encryptField` — the documented raw-SQL escape hatch — and `voltro db encrypt-column` wrote `encrypt(v)`. All three produce the same `enc:v1:` envelope and nothing distinguished them, so a value written by one and read by another either threw with the wrong diagnosis or came back subtly wrong (`decryptField` handed back the JSON encoding verbatim, quotes and all, raising nothing).
80
+
81
+ There is one encoding for every WRITE now, and every READ resolves BOTH forms — so **no data has to be rewritten and nothing is blocked**. That second half is the point: the old form is already on staging and production disks, and a fix that needs the rows rewritten before the app works is an outage with a migration attached.
82
+
83
+ Reading two forms is deterministic, not a heuristic. After decrypting, a parse failure is the raw form; a parse to a STRING is the JSON form; a parse to a non-string depends on the column's declared type (a text column cannot hold a number, so `12345` is a raw string that parsed by accident). The one case nothing can separate — a raw secret whose literal text is `"abc"`, quotes included — is stated in the code rather than hidden.
84
+
85
+ **`voltro db encrypt-column` verified itself against the wrong decoder.** It wrote the raw form and checked it with `cipher.decrypt` — a decoder nothing reads these columns with — so it reported success over columns the app could not read. It round-trips through `decodeFieldValue` now, the same function the store calls. A self-check against a decoder the runtime does not use is not a weaker check; it is a second opinion from the same mistake.
86
+
87
+ The command also NORMALISES rows in the old encoding as it goes (reported separately from the ones it encrypts), so an operator does not write a script per column. It skips anything ambiguous and anything it cannot decrypt.
88
+
89
+ **The width pre-flight measured the wrong thing after the encoding changed.** It sized the ciphertext from the PLAINTEXT's byte length while the cipher is handed the JSON encoding — two characters more at minimum, and more for every escape. Measured on a real MariaDB: a 63-byte value in a `varchar(135)` passed the check and the UPDATE answered `ER_DATA_TOO_LONG`, which is the failure that check exists to prevent, mid-column with the rest already converted. It measures the encoded length now, and the refusal says "encodes to" rather than "is" so an operator measuring their own column finds the number it names.
90
+
91
+ **Two dialect defects, both found by running the command against real servers.** SQL Server reports `-1` for `NVARCHAR(MAX)` — its spelling of unbounded — and the pre-flight read it as a one-character column, so it refused the widest column the dialect has and printed `declared as -1` at the operator. And SQLITE has no `information_schema` at all: the shared catalog query died there with `Failed to prepare statement` and no statement attached, on a dialect the command claims to support. It uses `pragma_table_info` now, reporting no length because sqlite enforces none.
92
+
93
+ Measured end to end on postgres, mysql, mariadb, mssql and sqlite: a table holding plaintext, the old encoding and the current encoding side by side converts, every row decodes back to its original value, a re-run writes nothing, and a wrong key refuses with exit 1.
94
+
95
+ **Backups and restores were never affected and now say so.** `voltro data export` reads through the raw dialect store, so ciphertext travels verbatim in either encoding — pinned by a test, because a future change that wrapped that store would put plaintext credentials in a bundle.
96
+ - **@voltro/protocol, @voltro/cli** — Three findings from one consumer round, all of the same shape: something the framework knows and does not say.
97
+
98
+ **A decode failure on a GUARDED procedure now says the guard did not run.** The payload decodes before the handler, so a guard on a procedure with a malformed payload never gets the chance to refuse. A consumer auditing a guard called one with an incomplete payload, got a decode error instead of a `ScopeError`, and concluded the guard was not applied — the wrong conclusion in the dangerous direction. The title now carries `(guarded — the guard did NOT run: the payload failed to decode first, so this says nothing about access)`. It discloses nothing new: that a procedure is guarded is already visible to anyone who sends a VALID payload. An `openAccess:` declaration is not an enforced guard and gets no such sentence — `hasEnforcedGuard` is the one predicate, read by both the label and the wire error union, because two copies of that rule would disagree invisibly.
99
+
100
+ **`middleware.ts`'s `httpOnly` default is documented at the field, and warned about.** It defaults to `HttpOnly`, which is wrong for a session cookie a browser SDK reads back: Supabase's `createBrowserClient` reads `document.cookie`, so a forgotten `httpOnly: false` gives the browser a session it cannot see — the SSR render is perfect and the user is signed out at the first client-side call. The consumer only avoided shipping it because their probes already set the flag. `voltro dev` warns once per cookie when a session-shaped name is written with no `httpOnly` decision; an explicit decision either way silences it, because warning on a decision is how a diagnostic becomes noise.
101
+
102
+ **`voltro dev` restarts when `middleware.ts` changes.** It is loaded once per boot, that is documented, and a consumer read it and still lost an afternoon: they sabotaged the middleware, saw no change, and concluded it was not wired — in an environment where everything else hot-reloads. It now restarts through the same respawn a hard-restart field in `app.config.ts` uses, extracted so there is one copy of the `execArgv` inheritance and the signal forwarding.
103
+ - **@voltro/cli** — `middleware.ts` now produces ONE view of the request that every downstream reader takes. Previously only `buildLoaderQuery` saw the hook's result, while the loader context (`ctx.headers`), the SSR request snapshot (`useServerRequest()`) and the locale resolver kept reading the raw request — four readers, two answers, within eighty lines of one function.
104
+
105
+ The consequence was worse than an inconsistency: a hook that renews purely via `setCookies` — no `headers` at all, which is the normal shape for a cookie-session IdP and the reason the response half exists — moved nothing for the render that ran it. The rpc call still sent the old `Cookie` header, because a renewed cookie only reached the browser.
106
+
107
+ `setCookies` is applied to the cookie jar before the render, the `Cookie` header is rebuilt from that jar (an explicit `cookie` in the hook's own `headers` still wins), and `maxAge <= 0` deletes, so a hook that signs someone out renders them signed out. Both SSR boot paths shadow the raw headers out of scope after the hook runs, so a new reader added below is correct without knowing any of this.
108
+ - **@voltro/cli** — `voltro start` dropped `middleware.ts`'s `Set-Cookie` on **streamed** responses — which is the arm a plain `renderMode: 'ssr'` page takes, so it was the common case. The hook renewed the session server-side, the render used the fresh value, and the browser kept the consumed one. Against an IdP that rotates refresh tokens and detects reuse, that is worse than not renewing at all.
109
+
110
+ The cause is worth stating because it read as handled: a streamed response hands the socket to `stream(res)` and the caller never looks at the returned `headers`, so the `withCookies(...)` wrapper on that arm was dead code — sitting under a comment promising the cookies were written on every arm. The cookies now travel with the headers `streamSsrResponse` itself writes, and the dead wrapper is gone.
111
+
112
+ Found by booting real `voltro dev` and `voltro start` servers against a fixture and reading the response. Every unit test was green throughout, and the render's own HTML was correct — only the wire was wrong.
113
+
114
+ ---
115
+
116
+ ## [0.40.0] — 2026-08-16
117
+
118
+ ### ⚠ BREAKING
119
+
120
+ - **@voltro/client, @voltro/web** — A subscription whose COLD START failed is its own state — `failed: true`, `loading: false` — so "it is loading" is a true statement again.
121
+
122
+ The old shape left `loading: true` for a subscription where nothing was in flight and nothing more was coming. The type's own comment predicted the consequence:
123
+
124
+ > A cold-start failure leaves `loading` TRUE … so a component that branches on > `loading` alone renders a skeleton forever. Check `error` to break out of it.
125
+
126
+ A consumer quoted that back with the right conclusion: **a comment that predicts the misbehaviour of its own field is an API resting on discipline.** `loading` means "something is coming" everywhere else; here it meant "something is coming OR never again", and the escape hatch was a second field that the natural shape of a wrapper — pass `{ data, loading }` through — silently drops. They had three such wrappers. The framework had six, in `useWorkflow.ts`, and the compiler named all six the moment the state existed.
127
+
128
+ `failed` is a positive discriminant, so the check reads as one:
129
+
130
+ ```tsx
131
+ if (s.loading) return <Skeleton/>
132
+ if (s.failed) return <RetryPanel error={s.error}/>
133
+ return <Table rows={s.data}/>
134
+ ```
135
+
136
+ **BREAKING**: `!loading` no longer proves `data` is present, so every call site that reads `data` after a bare `loading` check is a type error naming file and line. Nothing fails silently. The codemod is `manual` on purpose — a transform could add `|| s.failed` everywhere and would be wrong about half of them, since an infinite skeleton is precisely what this removes.
137
+
138
+ **Measured blast radius**, because the estimate was worse than the reality: 20 errors inside `@voltro/client` (mostly its own `useWorkflow` wrapper and the type-tests) and **zero** in `@voltro/web`, `devtools-ui`, the devtools app, the cloud app, and all 45 templates. Most consumers were already using a `fallback` or a wrapper, which is what made the original defect so quiet.
139
+
140
+ Unchanged: a failure AFTER the first snapshot still leaves good data on screen with `error` set — only the cold start is `failed`. A `fallback` subscription still has `data` always present, so `failed` reports there rather than gating. `idle` stays opt-in by overload; `failed` is not opt-in, because any subscription's cold start can fail. And the state is terminal for one TRANSPORT: a reconnect discards the error and re-subscribes.
141
+ - **@voltro/protocol, @voltro/runtime, @voltro/voltro** — A guard refusing a caller whose credential was REJECTED now answers `Unauthenticated`, not `ScopeError`.
142
+
143
+ Measured by a consumer: a user's tab outlived their IdP's token lifetime. The strategy logged it plainly —
144
+
145
+ ```
146
+ WARN auth strategy "supabase" rejected request: supabase jwt expired
147
+ WARN mutation.tasks.update failed: missing required scope 'task:u:o'
148
+ ```
149
+
150
+ — and the wire said the caller lacked a scope. Technically true (an anonymous caller holds none) and it sends everyone who reads it into the permissions system while the problem is an expired session. They did that round; the subject was their administrator, and the same call with a fresh token worked.
151
+
152
+ **The obvious fix would have broken more than it fixed**, which is why this shape and not that one. Failing hard when a strategy rejects would break every `openAccess` procedure for anyone holding a stale cookie — a public page that needs no session at all would start refusing. So the FACT travels instead: a rejected credential stamps `credentialRejected` on the anonymous subject it falls back to, and only a guard that actually refuses spends it. `openAccess` never reaches that point and is untouched.
153
+
154
+ Three details worth knowing if you touch it:
155
+
156
+ - **The stamp happens AFTER the app's `fallback`.** That callback builds its own anonymous subject and knows nothing about the rejection; stamping before it would be silently discarded — the shape of every "wired on one path" defect in this codebase. - **ONE conversion point** (`asRefusal`), at the exit rather than at each `return`. Every branch builds the `ScopeError` it always built; one place decides what it MEANS. - **`Unauthenticated` is merged into the wire union** for guarded procedures AND guarded events, beside `ScopeError`. Without that it would be a tagged error the descriptor cannot represent, and the server would collapse it to `InternalError` — the defect another consumer reported the same week.
157
+
158
+ A caller who presented NO credential still gets `ScopeError`. Collapsing both would send a genuinely under-privileged user to the login page.
159
+
160
+ **Why this is BREAKING although nothing was removed.** Three published results gained a union member:
161
+
162
+ ```ts
163
+ checkGuards(…) // ScopeError | Unauthenticated | null (was ScopeError | null)
164
+ checkGuardsEffect(…) // Effect<ScopeError | Unauthenticated | null>
165
+ bindEvent(…) // Stream<…, ScopeError | Unauthenticated, …>
166
+ ```
167
+
168
+ The test for breaking is not "did a symbol disappear", it is whether code that COMPILED can stop compiling — and a widened return does that wherever the old union is named (`const refusal: ScopeError | null = checkGuards(…)`), or narrowed exhaustively. It was filed as `Added` first; the golden diff is what showed otherwise, and the rule is worth more than the classification that felt right. `anonymousSubject`'s new second parameter is OPTIONAL and breaks nothing.
169
+
170
+ `voltro update` carries you across it — codemod `0.40.0/02_rejected-credential-widens-guard-results`, a written note. A transform would widen each annotation, which compiles and keeps the reported behaviour: the decision at each site is what an expired session should do that a missing permission should not.
171
+
172
+ ### Added
173
+
174
+ - **@voltro/client, @voltro/web** — The client re-resolves `authHeaders` when the server says the credential was rejected — and `client.refreshAuth()` for an app that knows earlier.
175
+
176
+ `authHeaders` is resolved once per CONNECTION and attached per frame, so a tab open longer than the IdP's token lifetime keeps presenting a dead token until something reconnects. A consumer measured it: dragging a card on a board failed, their ADMINISTRATOR's token had simply expired while the page stood, and nothing in `@voltro/client` could force the re-resolve.
177
+
178
+ The trigger is the `Unauthenticated` error — which only became distinguishable from `ScopeError` in this same release. Before that the client could not have told "your session died" from "you lack a permission", and reconnecting on the second would have been wrong.
179
+
180
+ `refreshAuth()` is a SAME-SUBJECT rebuild, and the difference from `reconnect()` is one flag and a security boundary: `reconnect()` exists for a login / logout / tenant switch, where the next subject may be entitled to strictly LESS, so the cache must not be seeded from the old one. A token refresh is the same person with a fresh credential, so seeding is correct and the screen keeps its rows instead of blanking for the round trip. Getting that backwards is silent in both directions — seed on a subject change and you paint one user's rows into another's; refuse to seed on a refresh and every open screen blinks on every rotation.
181
+
182
+ The policy lives in ONE function (`wireAuthRefresh`) that every host wires, because "when do we reconnect on an auth error" is exactly the kind of decision this repo has watched drift when it was written twice. Two guards, answering different questions: a **rate** ceiling (one rebuild per window — a rejected mutation arrives alongside every rejected subscription on the page) and a **total** ceiling (stop after N refreshes with no successful call between, because at that point the credential is not stale, it is refused, and the answer is a sign-in screen rather than another socket).
183
+ - **@voltro/cli** — `middleware.ts` — a web app's one server-only hook, for renewing a credential before the SSR render uses it.
184
+
185
+ Reported: a consumer's SSR detail pages arrived empty on the first request of every day. Their cookie token had outlived the IdP's lifetime, the api resolved the caller to anonymous, and every `preload` on the page failed. They could not fix it in the app, and the reason is structural: `ctx.query` and every `preload` entry are bound from ONE cookie string **before any loader runs**, so a layout loader that renews the session cannot reach them — and a `type: 'web'` app has no auth middleware.
186
+
187
+ ```ts
188
+ // middleware.ts — web app root, server-only
189
+ export default async (req) => {
190
+ const fresh = await refreshSession(req.cookies['sb-session'])
191
+ if (!fresh) return
192
+ return {
193
+ headers: { authorization: `Bearer ${fresh.accessToken}` },
194
+ setCookies: [{ name: 'sb-session', value: fresh.cookie, maxAge: 3600 }],
195
+ }
196
+ }
197
+ ```
198
+
199
+ **Why not `app.config.ts`.** That file is imported into the CLIENT bundle, verbatim, the moment any api declares `authHeaders` — the thunk is a function, so it cannot be serialised. A hook that renews a session reaches for an IdP SDK by definition, so putting it there drags the server graph into the browser. The consumer proposed exactly that shape (`serverAuthHeaders` beside `authHeaders`) and it is the one place it cannot go.
200
+
201
+ **Why `setCookies` is not optional.** We asked whether writing cookies back was in scope, expecting the answer to be about a round trip. It was about correctness: Supabase ROTATES refresh tokens and detects reuse, so a hook that renews server-side and does not write the result back leaves the browser holding a consumed token. Without it the hook is not "slower but correct" — it can destroy the session.
202
+
203
+ **Deliberately not a general middleware.** It can replace credentials and set cookies. It cannot redirect, return a response, or rewrite a route — because authorization belongs on the API, which is the only thing that sees the data, and a web-side hook that can refuse a request becomes a second authorization layer beside the real one. A hook that cannot refuse also cannot be mistaken for a guard. For a login redirect, a loader already throws `RedirectError`.
204
+
205
+ Details worth knowing: only auth-shaped headers (`authorization`, `x-tenant`, `x-voltro-*`) are forwarded to the api, so a returned `host` or `content-length` cannot produce a failure that looks like anything but a header copy; cookies default to `HttpOnly` + `Path=/` + `SameSite=lax`; multiple cookies are written as separate header lines, never comma-joined (a cookie's `Expires` contains a comma); the file is loaded ONCE per boot; a failure to IMPORT is fatal rather than degrading to "no middleware", and a middleware that THROWS fails the request — the render must not proceed on the credential it was told to replace.
206
+
207
+ Wired on BOTH SSR boot paths (`voltro dev` and `voltro start`), with the cookies written on every response arm — streamed, buffered, redirect and 404. A partial application would renew a rotating token and drop it.
208
+ - **@voltro/testing** — `makeTestContext` supplies `ctx.events`, so an executor that publishes can be unit-tested at all.
209
+
210
+ `ctx.events` is a field PRODUCTION puts on every `AppContext`, and the test harness did not — so any handler containing `ctx.events.publish(...)` died on `Cannot read properties of undefined (reading 'publish')` the moment it ran under test.
211
+
212
+ **The shipped `api-durable` template demonstrates exactly that pattern** (publish inside the mutation's transaction, so it fires on COMMIT and not on rollback), and its own test passed anyway — because it called the executor with `await` instead of running it. An executor written in the Effect style RETURNS an Effect, and awaiting a non-thenable hands the object straight back, unrun. The assertion then failed on `row.status` being `undefined` and pointed at the assertion rather than at the call. Two defects propping each other up: the harness could not have run that handler, and the test never asked it to.
213
+
214
+ It is the REAL `makeEventPublisher` over a real `EventBus`, not a stub. A fake would re-implement the payload validation and the tenant stamping and would be wrong the first time either gains a case — the lesson `plugin-broadcast` paid for twice. `ctx.eventBus` is the read side:
215
+
216
+ ```ts
217
+ const seen = ctx.eventBus.subscribe(orderPlaced, { orderId })
218
+ await invoke(placeOrder, executor, input, ctx)
219
+ expect(seen.received).toHaveLength(1)
220
+ ```
221
+
222
+ One bus for the whole harness so a `withSubject` / `withTenant` re-scope still publishes where the test is listening; the PUBLISHER is per-subject, because the tenant it stamps is the caller's.
223
+
224
+ ### Fixed
225
+
226
+ - **@voltro/cli** — `voltro agents-md --force` no longer exits 0 when it wrote nothing.
227
+
228
+ Reported: a consumer's `agent-docs/` is owned by the pod (root). They ran the command as `admin`, and it **overwrote nothing, said nothing, and exited 0**. They read the unchanged file as "the framework has not fixed this yet" — it had — and lost a full round to it.
229
+
230
+ The cause was three `orElseSucceed`s in the agent-docs copy. `makeDirectory`, `readDirectory` and every `copyFile` degraded to success, so a destination the process could not write produced an empty run that reported itself as done. An unreadable source directory came back as `[]` and did the same.
231
+
232
+ Failures are collected and reported now, and the command **exits 1** when the seed is incomplete:
233
+
234
+ ```
235
+ agents-md: 12 file(s) could NOT be written — the seed is INCOMPLETE.
236
+ The commonest cause is ownership: a container wrote these as root and you are
237
+ running as someone else.
238
+ ```
239
+
240
+ `--force` is an explicit instruction to overwrite, so silently not overwriting is the one outcome that must never be reported as done. `stat` is the single remaining silent degrade, deliberately: a source entry that vanished mid-walk is not a write failure and must not fail the run.
241
+
242
+ Pinned in both directions — a real unwritable directory yields failures, a clean copy yields none, and a source guard asserts that `stat` is the ONLY call on that path allowed to swallow. Red-verified by restoring the original `orElseSucceed`.
243
+ - **@voltro/cli** — Every server-side loader context is now checked by the compiler, and the static prerender stopped handing loaders a context missing `search` and `headers`.
244
+
245
+ `ctx.isServer` shipped with a source-reading guard, and that guard had the defect it exists to prevent: it matched context literals by shape (`loader({` / `ctx: {`) and therefore found ONE of the two in `build.ts`, missing the one built as a typed arrow return. Its tripwire — "at least 5 sites" — passed, because a floor cannot tell 5-of-8 from 5-of-5. The gap was found by a parallel report, not by the guard.
246
+
247
+ The invariant moved from "the literal mentions `isServer`" to "the literal is CHECKED BY THE COMPILER": every server loader context is now `satisfies SegmentLoaderContext`, whose `isServer` is required. A site that forgets it is a type error naming the file and line — strictly stronger than any regex over shapes, and verified by removing one.
248
+
249
+ **It caught a second defect immediately.** The static prerender built its page loader context with only `params`, `pathname`, `signal` — no `search`, no `headers`, no `query` — while `LoaderContext.search` is declared `string`. A static page's loader reading `ctx.search` got `undefined` where the type promised a value. The segment context twenty lines above it in the same file already passed `search: ''` with a comment explaining why.
250
+
251
+ Two smaller things worth knowing if you touch the guard: the closing brace is part of its pattern because the bare phrase also appears in the comment explaining the rule (the first version counted its own documentation), and the CLI's `SegmentLoaderContext` mirror keeping `isServer` non-optional is what the whole enforcement rests on — `isServer?:` would make every `satisfies` pass while a forgetful site reports itself as the browser.
252
+ - **@voltro/protocol, @voltro/cli** — A guard's `ScopeError` reaches the client as `ScopeError` on a mutation, not as `InternalError`.
253
+
254
+ Measured by a consumer over the wire, same session, same foreign team:
255
+
256
+ | kind | declared `error:` | denial arrived as | |---|---|---| | query `webhooks.list` | `AccessDeniedError` | `_tag: 'ScopeError'` ✓ | | mutation `…updateReferenceLabels` | `AccessDeniedError` | `InternalError` ✗ | | the same mutation, after adding `ScopeError` to its union | | `_tag: 'ScopeError'` ✓ |
257
+
258
+ Their client maps `ScopeError` to *forbidden* and `InternalError` to *something went wrong*, so a permissions refusal looked like a crash — on every relationship-guarded write in the app.
259
+
260
+ **Their observation was exact; the mechanism was not, and the difference is where the fix goes.** They diagnosed it as "the merge only happens on the streaming path". `withGuardError` is called by every lifter, so the wire union carries `ScopeError` on both. What differs is a SECOND reader: the server refuses to ship a tagged error the descriptor cannot represent, collapsing it to `InternalError` rather than emitting a raw defect tree — and it was handed `descriptor.error`, the RAW declaration, while the union it protects is the WIDENED one. It judged against a narrower set than it had advertised. A query never reaches that check (it is delivered through `wireErrorFromCause`, which preserves the tag), which is exactly why the split fell along query/mutation.
261
+
262
+ `wireErrorUnion(descriptor, kind)` is now the single owner of "what can this procedure put on the wire", used by the lifters AND by both bind sites.
263
+
264
+ **Two more error classes were collapsed the same way, and neither was reported:**
265
+
266
+ - **`BusinessRuleViolation`** — unconditional for mutations. `withRuleError`'s own comment says it MUST be in the union "or the violation crosses the wire as an untyped defect". It was in the union, and collapsed before it got there. - **The `requiresApproval` refusals** — `ApprovalRequired` / `ApprovalExpired` / `ApprovalUnavailable`, so "parked for approval" was indistinguishable from "the server broke".
267
+
268
+ `openAccess:` still merges nothing: a procedure advertising a denial it cannot produce is what makes an error union stop meaning anything.
269
+
270
+ If you worked around this by declaring `ScopeError` yourself, the declaration is now redundant rather than wrong — the union is the same either way, and you can delete it whenever you like.
271
+
272
+ ---
273
+
42
274
  ## [0.39.1] — 2026-08-16
43
275
 
44
276
  ### Fixed
package/dist/index.d.ts CHANGED
@@ -241,6 +241,28 @@ export declare interface AsyncValidationResult {
241
241
  readonly message: string | undefined;
242
242
  }
243
243
 
244
+ export declare interface AuthRefreshHandle {
245
+ /** Stop listening. */
246
+ readonly dispose: () => void;
247
+ /** Call when a request SUCCEEDS — it resets the consecutive counter, which is
248
+ * what tells "the refresh fixed it" from "we are looping against a refusal".
249
+ * Optional for correctness (the counter is a ceiling either way) and the
250
+ * difference between recovering three times a day and recovering three times
251
+ * ever. */
252
+ readonly noteSuccess: () => void;
253
+ }
254
+
255
+ export declare interface AuthRefreshOptions {
256
+ /** Minimum gap between two refreshes. Default 15s — comfortably longer than
257
+ * a reconnect + first snapshot, so one expiry produces one rebuild. */
258
+ readonly cooldownMs?: number;
259
+ /** Give up after this many refreshes with no successful call between them.
260
+ * Default 3. */
261
+ readonly maxConsecutive?: number;
262
+ /** Injected in tests. */
263
+ readonly now?: () => number;
264
+ }
265
+
244
266
  /**
245
267
  * Auto-apply target as seen from the client. Identical shape to the
246
268
  * server's TargetSpec but with all schema generics erased (the client
@@ -988,6 +1010,11 @@ export declare const getMutationNotifier: () => MutationNotifier | undefined;
988
1010
  /** Read the current feed. Newest-first; up to MAX_MUTATIONS entries. */
989
1011
  export declare const getMutations: () => ReadonlyArray<MutationEvent>;
990
1012
 
1013
+ /** Is this the framework's `Unauthenticated`? Matched on `_tag`, the wire
1014
+ * contract, rather than on an instance — the error crosses a package boundary
1015
+ * and may be re-created by the decoder. */
1016
+ export declare const isUnauthenticated: (error: unknown) => boolean;
1017
+
991
1018
  /**
992
1019
  * Is this the loading baseline rather than a resolved api?
993
1020
  *
@@ -2367,6 +2394,37 @@ export declare interface SubscriptionCacheOptions {
2367
2394
  readonly errorBus?: RpcErrorBus;
2368
2395
  }
2369
2396
 
2397
+ /**
2398
+ * The cold start FAILED: something was asked, it errored, and no snapshot ever
2399
+ * arrived.
2400
+ *
2401
+ * This state used to be `SubscriptionPending` with `error` set — `loading: true`
2402
+ * for a subscription where nothing is in flight and nothing more is coming. The
2403
+ * type's own comment predicted the consequence ("a component that branches on
2404
+ * `loading` alone renders a skeleton forever"), which a consumer correctly
2405
+ * called out as an API resting on discipline: `loading` means "something is
2406
+ * coming" everywhere else, and here it meant "something is coming OR never
2407
+ * again". The escape hatch was a second field, and the natural shape of a
2408
+ * wrapper — pass `{ data, loading }` through — drops it. They had three such
2409
+ * wrappers; so did we, six times in `useWorkflow.ts`.
2410
+ *
2411
+ * `loading` is `false` here, so "it is loading" is a true statement again, and
2412
+ * `failed` makes the check positive rather than an inference from two absences.
2413
+ *
2414
+ * It is terminal for THIS transport only: a reconnect discards `baseError` and
2415
+ * re-subscribes, so the entry returns to pending on its own.
2416
+ */
2417
+ export declare interface SubscriptionFailed extends SubscriptionMeta {
2418
+ readonly data: undefined;
2419
+ readonly loading: false;
2420
+ readonly isEmpty: false;
2421
+ readonly idle: false;
2422
+ readonly failed: true;
2423
+ /** Non-optional here, and that is the point: this state exists precisely
2424
+ * because there is an error to show. */
2425
+ readonly error: unknown;
2426
+ }
2427
+
2370
2428
  /**
2371
2429
  * Deliberately NOT subscribed — `skip: true`.
2372
2430
  *
@@ -2393,6 +2451,8 @@ export declare interface SubscriptionIdle extends SubscriptionMeta {
2393
2451
  readonly loading: false;
2394
2452
  readonly isEmpty: false;
2395
2453
  readonly idle: true;
2454
+ /** Always `false` — nothing was asked, so nothing failed. */
2455
+ readonly failed: false;
2396
2456
  }
2397
2457
 
2398
2458
  /** The fields that mean the same thing in every subscription state. */
@@ -2464,6 +2524,8 @@ export declare interface SubscriptionOptions<T = unknown> {
2464
2524
  export declare interface SubscriptionPending extends SubscriptionMeta {
2465
2525
  readonly data: undefined;
2466
2526
  readonly loading: true;
2527
+ /** Always `false` while pending — something IS in flight. */
2528
+ readonly failed: false;
2467
2529
  /** Always `false` — this subscription IS asking, it just has no answer yet.
2468
2530
  * See {@link SubscriptionIdle} for the deliberately-not-asking case. */
2469
2531
  readonly idle: false;
@@ -2477,6 +2539,10 @@ export declare interface SubscriptionPending extends SubscriptionMeta {
2477
2539
  export declare interface SubscriptionSettled<T> extends SubscriptionMeta {
2478
2540
  readonly data: T;
2479
2541
  readonly loading: false;
2542
+ /** Always `false` — data arrived. A failure AFTER the first snapshot does not
2543
+ * replace good data (see `SubscriptionMeta.error`), so a settled state stays
2544
+ * settled. */
2545
+ readonly failed: false;
2480
2546
  /** Always `false` — data arrived. */
2481
2547
  readonly idle: false;
2482
2548
  /** The data that arrived is empty — an empty array, or a null value. */
@@ -2502,7 +2568,7 @@ export declare interface SubscriptionSettled<T> extends SubscriptionMeta {
2502
2568
  * Pass `fallback` to get {@link SubscriptionStateWithFallback} instead, where
2503
2569
  * `data` is always present and no narrowing is needed at all.
2504
2570
  */
2505
- export declare type SubscriptionState<T> = SubscriptionPending | SubscriptionSettled<T>;
2571
+ export declare type SubscriptionState<T> = SubscriptionPending | SubscriptionSettled<T> | SubscriptionFailed;
2506
2572
 
2507
2573
  /**
2508
2574
  * The result of `useSubscription` WITH a `fallback`. `data` is always present
@@ -2513,6 +2579,9 @@ export declare type SubscriptionState<T> = SubscriptionPending | SubscriptionSet
2513
2579
  export declare interface SubscriptionStateWithFallback<T> extends SubscriptionMeta {
2514
2580
  readonly data: T;
2515
2581
  readonly loading: boolean;
2582
+ /** True when the cold start failed. `data` is still the fallback, so there is
2583
+ * nothing to narrow — this reports, it does not gate. */
2584
+ readonly failed: boolean;
2516
2585
  /** True when `skip` is on. `data` is the fallback, and no request is in
2517
2586
  * flight — distinguishes "showing the fallback because we chose not to ask"
2518
2587
  * from "…because the answer has not arrived". */
@@ -2556,6 +2625,10 @@ export declare interface SupervisorHandle {
2556
2625
  * cookies) so a cookie-based login re-resolves the authenticated Subject
2557
2626
  * in place, without a page reload. No-op for UI-only (no-api) apps. */
2558
2627
  readonly reconnect: () => void;
2628
+ /** Re-resolve `authHeaders` and rebuild the transport, SAME subject — for a
2629
+ * rotated token on a long-lived tab. Unlike `reconnect()` this seeds the new
2630
+ * cache from the old one, because nobody's entitlement changed. */
2631
+ readonly refreshAuth: () => void;
2559
2632
  }
2560
2633
 
2561
2634
  export declare interface SupervisorOptions {
@@ -3281,6 +3354,16 @@ export declare interface WindowSpec {
3281
3354
  readonly bottomSpacer: number;
3282
3355
  }
3283
3356
 
3357
+ /**
3358
+ * Refresh the credential when the server says it was rejected.
3359
+ *
3360
+ * `refreshAuth` is the supervisor's SAME-SUBJECT rebuild — it re-resolves
3361
+ * `authHeaders` and keeps the cache, because a rotated token is the same person.
3362
+ * Do not pass `reconnect()` here: that one exists for a login / logout / tenant
3363
+ * switch and deliberately drops the cache.
3364
+ */
3365
+ export declare const wireAuthRefresh: (bus: RpcErrorBus, refreshAuth: () => void, options?: AuthRefreshOptions) => AuthRefreshHandle;
3366
+
3284
3367
  /** Attach a per-call `idempotency-key` header to an rpc call, MERGED over the
3285
3368
  * ambient headers (the auth headers seeded on the runtime) — never replacing
3286
3369
  * them. The server mutation funnel reads it to dedupe a retried mutation. */
package/dist/index.js CHANGED
@@ -500,12 +500,18 @@ var ne = /* @__PURE__ */ new Set(), D = (e) => {
500
500
  if (f || t.generation !== r) return;
501
501
  g(e);
502
502
  }
503
+ }, v = (e) => {
504
+ if (!f) for (let n of t) {
505
+ let t = d.get(n.name);
506
+ t && (e && (t.subjectMayHaveChanged = !0), t.retryToken += 1, t.generation += 1, t.failureCount = 0, De(t), _(n));
507
+ }
503
508
  };
504
509
  return t.length === 0 ? (r(/* @__PURE__ */ new Map(), !0), {
505
510
  dispose: () => {
506
511
  f = !0;
507
512
  },
508
- reconnect: () => {}
513
+ reconnect: () => {},
514
+ refreshAuth: () => {}
509
515
  }) : (c(() => {
510
516
  if (!f) for (let e of t) _(e);
511
517
  }), {
@@ -519,10 +525,10 @@ var ne = /* @__PURE__ */ new Set(), D = (e) => {
519
525
  }
520
526
  },
521
527
  reconnect: () => {
522
- if (!f) for (let e of t) {
523
- let t = d.get(e.name);
524
- t && (t.subjectMayHaveChanged = !0, t.retryToken += 1, t.generation += 1, t.failureCount = 0, De(t), _(e));
525
- }
528
+ v(!0);
529
+ },
530
+ refreshAuth: () => {
531
+ v(!1);
526
532
  }
527
533
  });
528
534
  }, Ae = ({ apis: e, children: t }) => {
@@ -900,7 +906,8 @@ function V(e, t, r = {}, i = {}) {
900
906
  data: S ? x.data : i.initialSnapshot,
901
907
  loading: !1,
902
908
  idle: a,
903
- isEmpty: S ? C : e
909
+ isEmpty: S ? C : e,
910
+ failed: !1
904
911
  };
905
912
  }
906
913
  return i.fallback === void 0 ? a ? {
@@ -908,25 +915,37 @@ function V(e, t, r = {}, i = {}) {
908
915
  data: void 0,
909
916
  loading: !1,
910
917
  isEmpty: !1,
911
- idle: !0
918
+ idle: !0,
919
+ failed: !1
912
920
  } : S ? {
913
921
  ...w,
914
922
  data: x.data,
915
923
  loading: !1,
916
924
  isEmpty: C,
917
- idle: !1
918
- } : {
925
+ idle: !1,
926
+ failed: !1
927
+ } : w.error === void 0 ? {
919
928
  ...w,
920
929
  data: void 0,
921
930
  loading: !0,
922
931
  isEmpty: !1,
923
- idle: !1
932
+ idle: !1,
933
+ failed: !1
934
+ } : {
935
+ ...w,
936
+ data: void 0,
937
+ loading: !1,
938
+ isEmpty: !1,
939
+ idle: !1,
940
+ failed: !0,
941
+ error: w.error
924
942
  } : {
925
943
  ...w,
926
944
  data: S ? x.data : i.fallback,
927
945
  loading: !S && !a,
928
946
  idle: a,
929
- isEmpty: C
947
+ isEmpty: C,
948
+ failed: !S && w.error !== void 0
930
949
  };
931
950
  }
932
951
  //#endregion
@@ -1890,7 +1909,7 @@ var tn = () => {
1890
1909
  ]);
1891
1910
  }, xn = (e, t) => {
1892
1911
  let n = V(e, "__voltro.workflow.run", t ? { id: t } : {}, { skip: t === void 0 });
1893
- return n.loading || n.idle ? {
1912
+ return n.loading || n.idle || n.failed ? {
1894
1913
  ...n,
1895
1914
  run: void 0
1896
1915
  } : {
@@ -1899,7 +1918,7 @@ var tn = () => {
1899
1918
  };
1900
1919
  }, Sn = (e, t = {}, n = {}) => {
1901
1920
  let r = V(e, "__voltro.workflow.runs", t, n);
1902
- return r.loading || r.idle ? {
1921
+ return r.loading || r.idle || r.failed ? {
1903
1922
  ...r,
1904
1923
  runs: []
1905
1924
  } : {
@@ -1908,7 +1927,7 @@ var tn = () => {
1908
1927
  };
1909
1928
  }, Cn = (e, t) => {
1910
1929
  let n = V(e, "__voltro.workflow.run.steps", t ? { runId: t } : {}, { skip: t === void 0 });
1911
- return n.loading || n.idle ? {
1930
+ return n.loading || n.idle || n.failed ? {
1912
1931
  ...n,
1913
1932
  steps: []
1914
1933
  } : {
@@ -1917,7 +1936,7 @@ var tn = () => {
1917
1936
  };
1918
1937
  }, wn = (e, t) => {
1919
1938
  let n = V(e, "__voltro.workflow.run.events", t ? { runId: t } : {}, { skip: t === void 0 });
1920
- return n.loading || n.idle ? {
1939
+ return n.loading || n.idle || n.failed ? {
1921
1940
  ...n,
1922
1941
  events: []
1923
1942
  } : {
@@ -1926,7 +1945,7 @@ var tn = () => {
1926
1945
  };
1927
1946
  }, Tn = wn, En = (e, t = {}, n = {}) => {
1928
1947
  let r = V(e, "__voltro.workflow.domainEvents", t, n);
1929
- return r.loading || r.idle ? {
1948
+ return r.loading || r.idle || r.failed ? {
1930
1949
  ...r,
1931
1950
  events: []
1932
1951
  } : {
@@ -1935,7 +1954,7 @@ var tn = () => {
1935
1954
  };
1936
1955
  }, Dn = (e, t) => {
1937
1956
  let n = V(e, "__voltro.workflow.event.deliveries", t ? { eventId: t } : {}, { skip: t === void 0 });
1938
- return n.loading || n.idle ? {
1957
+ return n.loading || n.idle || n.failed ? {
1939
1958
  ...n,
1940
1959
  deliveries: []
1941
1960
  } : {
@@ -2205,38 +2224,50 @@ var tn = () => {
2205
2224
  return n(() => {
2206
2225
  t.refreshAll(r);
2207
2226
  }, [t, r]);
2208
- }, Wn = /* @__PURE__ */ new Set(), Gn = (e) => {
2209
- for (let t of Wn) try {
2227
+ }, Wn = (e) => e?._tag === "Unauthenticated", Gn = (e, t, n = {}) => {
2228
+ let r = n.cooldownMs ?? 15e3, i = n.maxConsecutive ?? 3, a = n.now ?? (() => Date.now()), o = -Infinity, s = 0;
2229
+ return {
2230
+ dispose: e.on((e) => {
2231
+ if (!Wn(e.error) || s >= i) return;
2232
+ let n = a();
2233
+ n - o < r || (o = n, s += 1, t());
2234
+ }),
2235
+ noteSuccess: () => {
2236
+ s = 0;
2237
+ }
2238
+ };
2239
+ }, Kn = /* @__PURE__ */ new Set(), qn = (e) => {
2240
+ for (let t of Kn) try {
2210
2241
  t(e);
2211
2242
  } catch {}
2212
- }, Kn = (e) => (Wn.add(e), () => {
2213
- Wn.delete(e);
2214
- }), qn = (e, t) => {
2215
- Gn({
2243
+ }, Jn = (e) => (Kn.add(e), () => {
2244
+ Kn.delete(e);
2245
+ }), Yn = (e, t) => {
2246
+ qn({
2216
2247
  error: e,
2217
2248
  source: "manual",
2218
2249
  ...t ? { context: t } : {}
2219
2250
  });
2220
- }, Jn = (e, t) => {
2251
+ }, Xn = (e, t) => {
2221
2252
  let { errorBus: n } = N(e);
2222
2253
  a(() => n.on(t), [n, t]);
2223
- }, Yn = "#/$defs/", Xn = (e) => e.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/\s+/g, " ").trim().replace(/^./, (e) => e.toUpperCase()), Z = (e, t) => {
2254
+ }, Zn = "#/$defs/", Qn = (e) => e.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/\s+/g, " ").trim().replace(/^./, (e) => e.toUpperCase()), Z = (e, t) => {
2224
2255
  let n = e;
2225
2256
  for (let e = 0; e < 8; e += 1) {
2226
2257
  let e = n.$ref;
2227
- if (typeof e != "string" || !e.startsWith(Yn)) return n;
2258
+ if (typeof e != "string" || !e.startsWith(Zn)) return n;
2228
2259
  let r = t[e.slice(8)];
2229
2260
  if (!r || typeof r != "object") return n;
2230
2261
  n = r;
2231
2262
  }
2232
2263
  return n;
2233
- }, Zn = (e) => {
2264
+ }, $n = (e) => {
2234
2265
  if (!e || typeof e != "object") return !1;
2235
2266
  let t = e;
2236
2267
  if (t.type === "null" || t.const === null) return !0;
2237
2268
  let n = t.enum;
2238
2269
  return Array.isArray(n) && n.length === 1 && n[0] === null;
2239
- }, Qn = (e, t) => {
2270
+ }, er = (e, t) => {
2240
2271
  let n = e.type;
2241
2272
  if (Array.isArray(n) && n.includes("null")) {
2242
2273
  let t = n.filter((e) => e !== "null");
@@ -2251,7 +2282,7 @@ var tn = () => {
2251
2282
  for (let n of ["anyOf", "oneOf"]) {
2252
2283
  let r = e[n];
2253
2284
  if (!Array.isArray(r)) continue;
2254
- let i = r.filter((e) => !Zn(e));
2285
+ let i = r.filter((e) => !$n(e));
2255
2286
  if (i.length !== r.length) return i.length === 1 ? {
2256
2287
  node: Z(i[0], t),
2257
2288
  nullable: !0
@@ -2267,14 +2298,14 @@ var tn = () => {
2267
2298
  node: e,
2268
2299
  nullable: !1
2269
2300
  };
2270
- }, $n = (e) => e.map((e) => ({
2301
+ }, tr = (e) => e.map((e) => ({
2271
2302
  value: String(e),
2272
- label: Xn(String(e))
2273
- })), er = (e) => {
2303
+ label: Qn(String(e))
2304
+ })), nr = (e) => {
2274
2305
  let t = e.enum;
2275
2306
  if (Array.isArray(t) && t.length > 0) return {
2276
2307
  widget: "select",
2277
- options: $n(t)
2308
+ options: tr(t)
2278
2309
  };
2279
2310
  let n = e.type, r = Array.isArray(n) ? n.find((e) => e !== "null") : n, i = e.format;
2280
2311
  switch (r) {
@@ -2285,38 +2316,38 @@ var tn = () => {
2285
2316
  case "array": return { widget: "multi-select" };
2286
2317
  default: return { widget: "custom" };
2287
2318
  }
2288
- }, tr = (e, t, n) => Object.entries(e).map(([e, r]) => {
2289
- let { node: i, nullable: a } = Qn(Z(r, n), n), o = Z(i, n), { widget: s, options: c } = er(o);
2319
+ }, rr = (e, t, n) => Object.entries(e).map(([e, r]) => {
2320
+ let { node: i, nullable: a } = er(Z(r, n), n), o = Z(i, n), { widget: s, options: c } = nr(o);
2290
2321
  return {
2291
2322
  name: e,
2292
- label: Xn(e),
2323
+ label: Qn(e),
2293
2324
  widget: s,
2294
2325
  required: t.has(e),
2295
2326
  nullable: a,
2296
2327
  ...c ? { options: c } : {},
2297
2328
  jsonSchema: o
2298
2329
  };
2299
- }), nr = (e) => {
2330
+ }), ir = (e) => {
2300
2331
  try {
2301
2332
  return g.make(e);
2302
2333
  } catch {
2303
2334
  return;
2304
2335
  }
2305
2336
  }, Q = (e) => {
2306
- let t = nr(e);
2337
+ let t = ir(e);
2307
2338
  if (t === void 0) return [];
2308
2339
  let n = t.$defs ?? {}, r = Z(t, n), i = r.properties;
2309
- return i ? tr(i, new Set(Array.isArray(r.required) ? r.required : []), n) : [];
2310
- }, rr = (e) => {
2311
- let t = nr(e);
2340
+ return i ? rr(i, new Set(Array.isArray(r.required) ? r.required : []), n) : [];
2341
+ }, ar = (e) => {
2342
+ let t = ir(e);
2312
2343
  if (t === void 0) return [];
2313
2344
  let n = t.$defs ?? {}, r = Z(t, n);
2314
2345
  if (r.type !== "array") return [];
2315
2346
  let i = r.items;
2316
2347
  if (!i || typeof i != "object") return [];
2317
2348
  let a = Z(i, n), o = a.properties;
2318
- return o ? tr(o, new Set(Array.isArray(a.required) ? a.required : []), n) : [];
2319
- }, ir = (e, t) => {
2349
+ return o ? rr(o, new Set(Array.isArray(a.required) ? a.required : []), n) : [];
2350
+ }, or = (e, t) => {
2320
2351
  let n = b.decodeUnknownEither(e, { errors: "all" })(t);
2321
2352
  if (n._tag === "Right") return {
2322
2353
  valid: !0,
@@ -2331,7 +2362,7 @@ var tn = () => {
2331
2362
  valid: !1,
2332
2363
  errors: r
2333
2364
  };
2334
- }, ar = (e, t, r) => {
2365
+ }, sr = (e, t, r) => {
2335
2366
  let i = N(e), a = K(e, t), l = r.schema ?? i.descriptors[t]?.input;
2336
2367
  process.env.NODE_ENV !== "production" && l === void 0 && console.error(`[@voltro/client] useFormBinding('${e}', '${t}'): no input schema. Pass options.schema, or mount the descriptor so its input reaches the client. Rendering no fields; submit skips client-side validation.`);
2337
2368
  let u = o(() => l ? Q(l) : [], [l]), d = s(r.defaults ?? {}), [f, p] = c(d.current), [m, h] = c({}), g = n((e, t) => {
@@ -2348,7 +2379,7 @@ var tn = () => {
2348
2379
  p(d.current), h({});
2349
2380
  }, []), y = n(async () => {
2350
2381
  if (l !== void 0) {
2351
- let e = ir(l, f);
2382
+ let e = or(l, f);
2352
2383
  if (h(e.errors), !e.valid) return;
2353
2384
  }
2354
2385
  return a.mutate(f);
@@ -2361,7 +2392,7 @@ var tn = () => {
2361
2392
  fields: u,
2362
2393
  values: f,
2363
2394
  errors: m,
2364
- isValid: o(() => l === void 0 || ir(l, f).valid, [l, f]),
2395
+ isValid: o(() => l === void 0 || or(l, f).valid, [l, f]),
2365
2396
  pending: a.pending,
2366
2397
  submitError: a.error,
2367
2398
  data: a.data,
@@ -2370,13 +2401,13 @@ var tn = () => {
2370
2401
  reset: v,
2371
2402
  submit: y
2372
2403
  };
2373
- }, or = (e, t, n) => e.map((e) => {
2404
+ }, cr = (e, t, n) => e.map((e) => {
2374
2405
  let r = String(e[n] ?? ""), i = e[t];
2375
2406
  return {
2376
2407
  value: r,
2377
2408
  label: i == null ? r : String(i)
2378
2409
  };
2379
- }), sr = (e, t, r = {}) => {
2410
+ }), lr = (e, t, r = {}) => {
2380
2411
  let i = r.debounceMs ?? 200, s = r.labelField ?? "name", l = r.valueField ?? "id", u = r.input ?? ((e) => ({ q: e })), [d, f] = c(r.initialTerm ?? ""), [p, m] = c(d);
2381
2412
  a(() => {
2382
2413
  if (d === p) return;
@@ -2387,7 +2418,7 @@ var tn = () => {
2387
2418
  p,
2388
2419
  i
2389
2420
  ]);
2390
- let h = r.skipUntilTerm === !0 && p.trim() === "", g = V(e, t, o(() => u(p), [u, p]), { skip: h }), _ = o(() => or(g.data ?? [], s, l), [
2421
+ let h = r.skipUntilTerm === !0 && p.trim() === "", g = V(e, t, o(() => u(p), [u, p]), { skip: h }), _ = o(() => cr(g.data ?? [], s, l), [
2391
2422
  g.data,
2392
2423
  s,
2393
2424
  l
@@ -2398,13 +2429,13 @@ var tn = () => {
2398
2429
  term: d,
2399
2430
  search: v
2400
2431
  };
2401
- }, cr = (e, t) => e === t ? 0 : e == null ? 1 : t == null || e < t ? -1 : 1, lr = (e, t, r = {}) => {
2432
+ }, ur = (e, t) => e === t ? 0 : e == null ? 1 : t == null || e < t ? -1 : 1, dr = (e, t, r = {}) => {
2402
2433
  let i = N(e), [a, s] = c(r.pageSize), l = V(e, t, o(() => a === void 0 ? r.input ?? {} : {
2403
2434
  ...r.input,
2404
2435
  limit: a
2405
2436
  }, [r.input, a])), u = i.descriptors[t]?.output, d = n(() => {
2406
2437
  r.pageSize !== void 0 && s((e) => (e ?? r.pageSize) + r.pageSize);
2407
- }, [r.pageSize]), f = o(() => r.columns ?? (u === void 0 ? [] : rr(u)), [r.columns, u]), [p, m] = c(r.initialSort), h = n((e) => {
2438
+ }, [r.pageSize]), f = o(() => r.columns ?? (u === void 0 ? [] : ar(u)), [r.columns, u]), [p, m] = c(r.initialSort), h = n((e) => {
2408
2439
  m((t) => t?.column === e ? {
2409
2440
  column: e,
2410
2441
  direction: t.direction === "asc" ? "desc" : "asc"
@@ -2419,7 +2450,7 @@ var tn = () => {
2419
2450
  let e = l.data ?? [];
2420
2451
  if (p === void 0) return e;
2421
2452
  let t = p.direction === "asc" ? 1 : -1;
2422
- return [...e].sort((e, n) => cr(e[p.column], n[p.column]) * t);
2453
+ return [...e].sort((e, n) => ur(e[p.column], n[p.column]) * t);
2423
2454
  }, [l.data, p]),
2424
2455
  loading: l.data === void 0,
2425
2456
  error: l.error,
@@ -2428,13 +2459,13 @@ var tn = () => {
2428
2459
  loadMore: d,
2429
2460
  hasMore: a !== void 0 && (l.data?.length ?? 0) >= a
2430
2461
  };
2431
- }, ur = (e, t, n, r) => {
2462
+ }, fr = (e, t, n, r) => {
2432
2463
  let i = e.replace(/\/$/, ""), a = new URLSearchParams({
2433
2464
  table: t,
2434
2465
  id: n
2435
2466
  });
2436
2467
  return r !== void 0 && a.set("column", r), `${i}/_voltro/inspect/provenance?${a.toString()}`;
2437
- }, dr = ur, fr = (e, t, n, r) => {
2468
+ }, pr = fr, mr = (e, t, n, r) => {
2438
2469
  let { inspectBaseUrl: i } = N(e), [o, s] = c({
2439
2470
  data: void 0,
2440
2471
  loading: !0,
@@ -2447,7 +2478,7 @@ var tn = () => {
2447
2478
  loading: !0,
2448
2479
  error: void 0
2449
2480
  });
2450
- let a = ur(i ?? "", t, n, r);
2481
+ let a = fr(i ?? "", t, n, r);
2451
2482
  return fetch(a).then(async (e) => {
2452
2483
  if (!e.ok) throw Error(`provenance fetch failed: HTTP ${e.status}`);
2453
2484
  return await e.json();
@@ -2473,11 +2504,11 @@ var tn = () => {
2473
2504
  n,
2474
2505
  r
2475
2506
  ]), o;
2476
- }, pr = "admin:full", mr = (e, t) => e.includes("admin:full") ? !0 : (typeof t == "string" ? [t] : t).every((t) => e.includes(t)), hr = (e, t) => t.length === 0 || e.includes("admin:full") ? !0 : t.some((t) => e.includes(t)), gr = e({ scopes: [] });
2477
- function _r(e) {
2478
- return t(gr.Provider, { value: { scopes: e.scopes } }, e.children);
2507
+ }, hr = "admin:full", gr = (e, t) => e.includes("admin:full") ? !0 : (typeof t == "string" ? [t] : t).every((t) => e.includes(t)), _r = (e, t) => t.length === 0 || e.includes("admin:full") ? !0 : t.some((t) => e.includes(t)), vr = e({ scopes: [] });
2508
+ function yr(e) {
2509
+ return t(vr.Provider, { value: { scopes: e.scopes } }, e.children);
2479
2510
  }
2480
- var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e), br = (e) => `${e.replace(/\/$/, "")}/_voltro/inspect/manifest`, xr = (e) => {
2511
+ var $ = () => r(vr), br = (e) => gr($().scopes, e), xr = (e) => _r($().scopes, e), Sr = (e) => `${e.replace(/\/$/, "")}/_voltro/inspect/manifest`, Cr = (e) => {
2481
2512
  let { inspectBaseUrl: t } = N(e), [n, r] = c({
2482
2513
  manifest: void 0,
2483
2514
  loading: !0,
@@ -2489,7 +2520,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2489
2520
  manifest: void 0,
2490
2521
  loading: !0,
2491
2522
  error: void 0
2492
- }), fetch(br(t ?? "")).then(async (e) => {
2523
+ }), fetch(Sr(t ?? "")).then(async (e) => {
2493
2524
  if (!e.ok) throw Error(`manifest fetch failed: HTTP ${e.status}`);
2494
2525
  return await e.json();
2495
2526
  }).then((t) => {
@@ -2508,7 +2539,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2508
2539
  e = !0;
2509
2540
  };
2510
2541
  }, [e, t]), n;
2511
- }, Sr = (e, t) => t.scope.length === 0 || (t.mode === "any" ? t.scope.some((t) => e.includes(t)) : t.scope.every((t) => e.includes(t))), Cr = (e, t) => {
2542
+ }, wr = (e, t) => t.scope.length === 0 || (t.mode === "any" ? t.scope.some((t) => e.includes(t)) : t.scope.every((t) => e.includes(t))), Tr = (e, t) => {
2512
2543
  if (e === void 0) return "unknown";
2513
2544
  if (t.includes("admin:full") || e.length === 0) return "allowed";
2514
2545
  let n = !1;
@@ -2517,7 +2548,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2517
2548
  n = !0;
2518
2549
  continue;
2519
2550
  }
2520
- if (!Sr(t, r)) {
2551
+ if (!wr(t, r)) {
2521
2552
  if (r.resourceScoped) {
2522
2553
  n = !0;
2523
2554
  continue;
@@ -2526,13 +2557,13 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2526
2557
  }
2527
2558
  }
2528
2559
  return n ? "unknown" : "allowed";
2529
- }, wr = (e) => (e ?? []).flatMap((e) => e.kind === "scope" ? [...e.scope] : []), Tr = (e) => {
2560
+ }, Er = (e) => (e ?? []).flatMap((e) => e.kind === "scope" ? [...e.scope] : []), Dr = (e) => {
2530
2561
  for (let t of e ?? []) if (t.kind === "open") return t.reason;
2531
- }, Er = (e) => Cr(e, $().scopes), Dr = (e, t) => Array.isArray(e) ? e.includes(t) : e === t, Or = (e, t, n) => e.targets?.some((e) => e.table === t && e.op === n) ?? !1, kr = (e) => e === void 0 ? {} : {
2562
+ }, Or = (e) => Tr(e, $().scopes), kr = (e, t) => Array.isArray(e) ? e.includes(t) : e === t, Ar = (e, t, n) => e.targets?.some((e) => e.table === t && e.op === n) ?? !1, jr = (e) => e === void 0 ? {} : {
2532
2563
  tag: e.tag,
2533
2564
  ...e.guards === void 0 ? {} : { guards: e.guards }
2534
- }, Ar = (e) => e.tables.filter((e) => !e.framework).map((t) => {
2535
- let n = e.procedures.find((e) => e.kind === "query" && Dr(e.source, t.name)), r = e.procedures.find((e) => e.kind === "mutation" && Or(e, t.name, "insert")), i = e.procedures.find((e) => e.kind === "mutation" && Or(e, t.name, "update")), a = e.procedures.find((e) => e.kind === "mutation" && Or(e, t.name, "delete")), o = t.pkColumn ?? (t.columns.some((e) => e.name === "id") ? "id" : void 0);
2565
+ }, Mr = (e) => e.tables.filter((e) => !e.framework).map((t) => {
2566
+ let n = e.procedures.find((e) => e.kind === "query" && kr(e.source, t.name)), r = e.procedures.find((e) => e.kind === "mutation" && Ar(e, t.name, "insert")), i = e.procedures.find((e) => e.kind === "mutation" && Ar(e, t.name, "update")), a = e.procedures.find((e) => e.kind === "mutation" && Ar(e, t.name, "delete")), o = t.pkColumn ?? (t.columns.some((e) => e.name === "id") ? "id" : void 0);
2536
2567
  return {
2537
2568
  table: t.name,
2538
2569
  columns: t.columns.filter((e) => e.serverOnly !== !0),
@@ -2541,12 +2572,12 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2541
2572
  reactive: t.reactive,
2542
2573
  ...o === void 0 ? {} : { pkColumn: o },
2543
2574
  editable: (t.editable ?? !0) && o !== void 0,
2544
- list: kr(n),
2545
- create: kr(r),
2546
- update: kr(i),
2547
- delete: kr(a)
2575
+ list: jr(n),
2576
+ create: jr(r),
2577
+ update: jr(i),
2578
+ delete: jr(a)
2548
2579
  };
2549
- }), jr = (e) => {
2580
+ }), Nr = (e) => {
2550
2581
  let [t, r] = c([]), [i, a] = c([]), s = n((e) => {
2551
2582
  r((t) => [...t, e]), a([]);
2552
2583
  }, []), l = n(async () => {
@@ -2574,8 +2605,8 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2574
2605
  l,
2575
2606
  u
2576
2607
  ]);
2577
- }, Mr = "__voltro.undo.log", Nr = "__voltro.undo.apply", Pr = "__voltro.undo.redo", Fr = (e, t) => {
2578
- let r = t?.limit, { data: i } = V(e, Mr, r === void 0 ? {} : { limit: r }), a = K(e, Nr), o = K(e, Pr), s = i ?? [], c = s.find((e) => !e.undone && !e.crossesAction), l = s.find((e) => e.undone), u = n(async (e) => {
2608
+ }, Pr = "__voltro.undo.log", Fr = "__voltro.undo.apply", Ir = "__voltro.undo.redo", Lr = (e, t) => {
2609
+ let r = t?.limit, { data: i } = V(e, Pr, r === void 0 ? {} : { limit: r }), a = K(e, Fr), o = K(e, Ir), s = i ?? [], c = s.find((e) => !e.undone && !e.crossesAction), l = s.find((e) => e.undone), u = n(async (e) => {
2579
2610
  await a.mutate({ invocationId: e });
2580
2611
  }, [a]), d = n(async (e) => {
2581
2612
  await o.mutate({ invocationId: e });
@@ -2594,21 +2625,21 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2594
2625
  undoLast: f,
2595
2626
  redoLast: p
2596
2627
  };
2597
- }, Ir = (e, t) => ({
2628
+ }, Rr = (e, t) => ({
2598
2629
  name: e,
2599
2630
  map: t
2600
- }), Lr = (e, t) => e === void 0 ? null : typeof e == "string" ? { event: e } : e(t), Rr = /* @__PURE__ */ new Set(["onMount", "onUnmount"]), zr = (e, t, n) => {
2631
+ }), zr = (e, t) => e === void 0 ? null : typeof e == "string" ? { event: e } : e(t), Br = /* @__PURE__ */ new Set(["onMount", "onUnmount"]), Vr = (e, t, n) => {
2601
2632
  let r = { ...t };
2602
2633
  for (let [i, a] of Object.entries(e.map)) {
2603
- if (Rr.has(i) || a === void 0) continue;
2634
+ if (Br.has(i) || a === void 0) continue;
2604
2635
  let e = t[i];
2605
2636
  r[i] = (...r) => {
2606
- let i = Lr(a, t);
2637
+ let i = zr(a, t);
2607
2638
  if (i !== null && n(i), typeof e == "function") return e(...r);
2608
2639
  };
2609
2640
  }
2610
2641
  return r;
2611
- }, Br = (e, t, n) => {
2642
+ }, Hr = (e, t, n) => {
2612
2643
  let r = s({
2613
2644
  spec: e,
2614
2645
  props: t,
@@ -2619,46 +2650,46 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2619
2650
  props: t,
2620
2651
  sink: n
2621
2652
  }, a(() => {
2622
- let e = r.current, t = Lr(e.spec.map.onMount, e.props);
2653
+ let e = r.current, t = zr(e.spec.map.onMount, e.props);
2623
2654
  return t !== null && e.sink(t), () => {
2624
- let e = r.current, t = Lr(e.spec.map.onUnmount, e.props);
2655
+ let e = r.current, t = zr(e.spec.map.onUnmount, e.props);
2625
2656
  t !== null && e.sink(t);
2626
2657
  };
2627
- }, []), o(() => zr(e, t, n), [
2658
+ }, []), o(() => Vr(e, t, n), [
2628
2659
  e,
2629
2660
  t,
2630
2661
  n
2631
2662
  ]);
2632
- }, Vr = (e, t) => {
2663
+ }, Ur = (e, t) => {
2633
2664
  let n = N(e).descriptors[t]?.input;
2634
2665
  return o(() => n === void 0 ? [] : Q(n), [n]);
2635
- }, Hr = (e, t) => {
2666
+ }, Wr = (e, t) => {
2636
2667
  let n = N(e).descriptors[t]?.output;
2637
- return o(() => n === void 0 ? [] : rr(n), [n]);
2638
- }, Ur = (e, t) => {
2668
+ return o(() => n === void 0 ? [] : ar(n), [n]);
2669
+ }, Gr = (e, t) => {
2639
2670
  if (e === t) return !0;
2640
2671
  if (e.length !== t.length) return !1;
2641
2672
  for (let n = 0; n < e.length; n += 1) if (!Object.is(e[n], t[n])) return !1;
2642
2673
  return !0;
2643
- }, Wr = (e) => Object.keys(e).sort().map((t) => e[t]), Gr = (e, t) => {
2644
- let n = s(null), r = Wr(e);
2645
- return (n.current === null || !Ur(n.current.key, r)) && (n.current = {
2674
+ }, Kr = (e) => Object.keys(e).sort().map((t) => e[t]), qr = (e, t) => {
2675
+ let n = s(null), r = Kr(e);
2676
+ return (n.current === null || !Gr(n.current.key, r)) && (n.current = {
2646
2677
  key: r,
2647
2678
  value: t(e)
2648
2679
  }), n.current.value;
2649
- }, Kr = (e, t, n, r = {}) => {
2680
+ }, Jr = (e, t, n, r = {}) => {
2650
2681
  let i = V(e, t, { ...n }, r);
2651
2682
  return o(() => ({
2652
2683
  allowed: i.data?.allowed === !0,
2653
2684
  pending: i.data === void 0
2654
2685
  }), [i.data]);
2655
- }, qr = (e, t, n, r = {}) => {
2686
+ }, Yr = (e, t, n, r = {}) => {
2656
2687
  let i = V(e, t, { ...n }, r);
2657
2688
  return o(() => ({
2658
2689
  allowedIds: new Set(i.data?.allowedIds ?? []),
2659
2690
  pending: i.data === void 0
2660
2691
  }), [i.data]);
2661
- }, Jr = (e) => {
2692
+ }, Xr = (e) => {
2662
2693
  switch (e) {
2663
2694
  case "select":
2664
2695
  case "radio":
@@ -2674,25 +2705,25 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2674
2705
  case "switch": return "boolean";
2675
2706
  default: return null;
2676
2707
  }
2677
- }, Yr = (e) => Q(e).map((e) => {
2678
- let t = Jr(e.widget);
2708
+ }, Zr = (e) => Q(e).map((e) => {
2709
+ let t = Xr(e.widget);
2679
2710
  return t === null ? null : {
2680
2711
  name: e.name,
2681
2712
  label: e.label,
2682
2713
  kind: t,
2683
2714
  ...e.options ? { options: e.options } : {}
2684
2715
  };
2685
- }).filter((e) => e !== null), Xr = (e) => {
2716
+ }).filter((e) => e !== null), Qr = (e) => {
2686
2717
  let t = {};
2687
2718
  for (let [n, r] of Object.entries(e)) r === void 0 || r === "" || Array.isArray(r) && r.length === 0 || (t[n] = r);
2688
2719
  return t;
2689
- }, Zr = (e, t, r = {}) => {
2690
- let i = N(e).descriptors[t]?.input, a = o(() => i === void 0 ? [] : Yr(i), [i]), [s, l] = c(r.initial ?? {}), u = n((e, t) => {
2691
- l((n) => Xr({
2720
+ }, $r = (e, t, r = {}) => {
2721
+ let i = N(e).descriptors[t]?.input, a = o(() => i === void 0 ? [] : Zr(i), [i]), [s, l] = c(r.initial ?? {}), u = n((e, t) => {
2722
+ l((n) => Qr({
2692
2723
  ...n,
2693
2724
  [e]: t
2694
2725
  }));
2695
- }, []), d = n(() => l({}), []), f = V(e, t, o(() => Xr(s), [s]));
2726
+ }, []), d = n(() => l({}), []), f = V(e, t, o(() => Qr(s), [s]));
2696
2727
  return {
2697
2728
  filters: a,
2698
2729
  values: s,
@@ -2703,20 +2734,20 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2703
2734
  loading: f.data === void 0,
2704
2735
  error: f.error
2705
2736
  };
2706
- }, Qr = (e, t, n = {}) => {
2737
+ }, ei = (e, t, n = {}) => {
2707
2738
  let r = V(e, t, n), i = r.data;
2708
2739
  return {
2709
2740
  record: Array.isArray(i) ? i[0] : i,
2710
2741
  loading: i === void 0,
2711
2742
  error: r.error
2712
2743
  };
2713
- }, $r = (e, t = 300) => {
2744
+ }, ti = (e, t = 300) => {
2714
2745
  let [n, r] = c(e);
2715
2746
  return a(() => {
2716
2747
  let n = setTimeout(() => r(e), t);
2717
2748
  return () => clearTimeout(n);
2718
2749
  }, [e, t]), n;
2719
- }, ei = (e) => {
2750
+ }, ni = (e) => {
2720
2751
  let { value: t, debouncedValue: n, data: r, interpret: i, skipEmpty: a = !0 } = e;
2721
2752
  if (a && t.trim() === "") return {
2722
2753
  status: "idle",
@@ -2734,19 +2765,19 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2734
2765
  valid: o.valid,
2735
2766
  message: o.message
2736
2767
  };
2737
- }, ti = (e, t, n, r) => {
2738
- let { input: i, interpret: a, debounceMs: s = 300, skipEmpty: c = !0 } = r, l = $r(n, s), u = c && l.trim() === "", d = V(e, t, o(() => i ? i(l) : { value: l }, [i, l]), { skip: u });
2739
- return ei({
2768
+ }, ri = (e, t, n, r) => {
2769
+ let { input: i, interpret: a, debounceMs: s = 300, skipEmpty: c = !0 } = r, l = ti(n, s), u = c && l.trim() === "", d = V(e, t, o(() => i ? i(l) : { value: l }, [i, l]), { skip: u });
2770
+ return ni({
2740
2771
  value: n,
2741
2772
  debouncedValue: l,
2742
2773
  data: u ? null : d.data,
2743
2774
  interpret: a,
2744
2775
  skipEmpty: c
2745
2776
  });
2746
- }, ni = (e, t) => ({
2777
+ }, ii = (e, t) => ({
2747
2778
  name: e,
2748
2779
  payload: t
2749
- }), ri = (e, t) => {
2780
+ }), ai = (e, t) => {
2750
2781
  let n = b.decodeUnknownEither(e.payload, { errors: "all" })(t);
2751
2782
  if (n._tag === "Right") return {
2752
2783
  valid: !0,
@@ -2758,15 +2789,15 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2758
2789
  valid: !1,
2759
2790
  errors: r
2760
2791
  };
2761
- }, ii = (e) => {
2792
+ }, oi = (e) => {
2762
2793
  let t = new Map(e.map((e) => [e.name, e]));
2763
2794
  return {
2764
2795
  names: [...t.keys()].sort(),
2765
2796
  get: (e) => t.get(e),
2766
2797
  events: e
2767
2798
  };
2768
- }, ai = (e, t) => {
2769
- let n = ii(e);
2799
+ }, si = (e, t) => {
2800
+ let n = oi(e);
2770
2801
  return {
2771
2802
  track: (e, r) => {
2772
2803
  let i = n.get(e);
@@ -2775,7 +2806,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2775
2806
  return;
2776
2807
  }
2777
2808
  if (process.env.NODE_ENV !== "production") {
2778
- let t = ri(i, r);
2809
+ let t = ai(i, r);
2779
2810
  t.valid || console.error(`[@voltro/client] analytics.track('${e}'): payload failed its schema`, t.errors);
2780
2811
  }
2781
2812
  t({
@@ -2786,7 +2817,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2786
2817
  names: n.names,
2787
2818
  catalog: n
2788
2819
  };
2789
- }, oi = (e, t) => {
2820
+ }, ci = (e, t) => {
2790
2821
  let r = q(e, t);
2791
2822
  return {
2792
2823
  preview: n((e) => r.run(e), [r]),
@@ -2794,34 +2825,34 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2794
2825
  pending: r.pending,
2795
2826
  error: r.error
2796
2827
  };
2797
- }, si = (e, t, n, r) => [...e, {
2828
+ }, li = (e, t, n, r) => [...e, {
2798
2829
  id: t,
2799
2830
  tag: n,
2800
2831
  input: r,
2801
2832
  status: "pending",
2802
2833
  attempts: 0
2803
- }], ci = (e, t, n) => e.map((e) => e.id === t ? {
2834
+ }], ui = (e, t, n) => e.map((e) => e.id === t ? {
2804
2835
  ...e,
2805
2836
  ...n
2806
- } : e), li = (e, t) => ci(e, t, { status: "sent" }), ui = (e, t, n) => e.map((e) => e.id === t ? {
2837
+ } : e), di = (e, t) => ui(e, t, { status: "sent" }), fi = (e, t, n) => e.map((e) => e.id === t ? {
2807
2838
  ...e,
2808
2839
  status: "failed",
2809
2840
  error: n,
2810
2841
  attempts: e.attempts + 1
2811
- } : e), di = (e, t, n) => ci(e, t, {
2842
+ } : e), pi = (e, t, n) => ui(e, t, {
2812
2843
  status: "conflict",
2813
2844
  error: n
2814
- }), fi = (e) => e.filter((e) => e.status !== "sent"), pi = (e) => {
2845
+ }), mi = (e) => e.filter((e) => e.status !== "sent"), hi = (e) => {
2815
2846
  let t = [];
2816
2847
  for (let n of e) {
2817
2848
  if (n.status === "conflict") break;
2818
2849
  (n.status === "pending" || n.status === "failed") && t.push(n);
2819
2850
  }
2820
2851
  return t;
2821
- }, mi = (e) => {
2852
+ }, gi = (e) => {
2822
2853
  let t = e;
2823
2854
  return t?.conflict === !0 || t?._tag === "UndoBoundaryError" && t?.boundary === "conflict";
2824
- }, hi = (e) => {
2855
+ }, _i = (e) => {
2825
2856
  let [t, n] = c(e ?? (typeof navigator < "u" ? navigator.onLine : !0));
2826
2857
  return a(() => {
2827
2858
  if (e !== void 0) {
@@ -2834,21 +2865,21 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2834
2865
  window.removeEventListener("online", t), window.removeEventListener("offline", r);
2835
2866
  };
2836
2867
  }, [e]), t;
2837
- }, gi = (e) => {
2838
- let { send: t, isConflict: r = mi, idFor: i } = e, [o, l] = c([]), u = hi(e.online), d = s(o);
2868
+ }, vi = (e) => {
2869
+ let { send: t, isConflict: r = gi, idFor: i } = e, [o, l] = c([]), u = _i(e.online), d = s(o);
2839
2870
  d.current = o;
2840
2871
  let f = s(0), p = n((e, t) => {
2841
2872
  let n = i?.() ?? `obx_${f.current++}_${e}`;
2842
- l((r) => si(r, n, e, t));
2873
+ l((r) => li(r, n, e, t));
2843
2874
  }, [i]), m = n(async () => {
2844
- for (let e of pi(d.current)) try {
2845
- await t(e), l((t) => li(t, e.id));
2875
+ for (let e of hi(d.current)) try {
2876
+ await t(e), l((t) => di(t, e.id));
2846
2877
  } catch (t) {
2847
2878
  if (r(t)) {
2848
- l((n) => di(n, e.id, t));
2879
+ l((n) => pi(n, e.id, t));
2849
2880
  break;
2850
2881
  }
2851
- l((n) => ui(n, e.id, t));
2882
+ l((n) => fi(n, e.id, t));
2852
2883
  }
2853
2884
  }, [t, r]);
2854
2885
  return a(() => {
@@ -2861,7 +2892,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2861
2892
  pending: o.filter((e) => e.status === "pending" || e.status === "failed").length,
2862
2893
  conflicts: o.filter((e) => e.status === "conflict")
2863
2894
  };
2864
- }, _i = (e) => {
2895
+ }, yi = (e) => {
2865
2896
  let { scrollTop: t, viewportHeight: n, rowHeight: r, overscan: i = 5, total: a } = e, o = r > 0 ? r : 1, s = Math.max(0, Math.floor(t / o)), c = Math.ceil(n / o), l = Math.max(0, s - i), u = s + c + i, d = a === void 0 ? u : Math.min(u, a);
2866
2897
  return {
2867
2898
  startIndex: l,
@@ -2871,8 +2902,8 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2871
2902
  topSpacer: l * r,
2872
2903
  bottomSpacer: a === void 0 ? 0 : Math.max(0, (a - d) * r)
2873
2904
  };
2874
- }, vi = (e, t, r) => {
2875
- let { rowHeight: i, viewportHeight: a, overscan: s, total: l, input: u } = r, [d, f] = c(0), p = o(() => _i({
2905
+ }, bi = (e, t, r) => {
2906
+ let { rowHeight: i, viewportHeight: a, overscan: s, total: l, input: u } = r, [d, f] = c(0), p = o(() => yi({
2876
2907
  scrollTop: d,
2877
2908
  viewportHeight: a,
2878
2909
  rowHeight: i,
@@ -2904,8 +2935,8 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2904
2935
  loading: m.data === void 0,
2905
2936
  error: m.error
2906
2937
  };
2907
- }, yi = () => typeof navigator > "u" || navigator.onLine, bi = (e) => {
2908
- let { errorBus: t } = N(e), [r, i] = c(yi), [o, l] = c(0), [u, d] = c(void 0), f = s(!0);
2938
+ }, xi = () => typeof navigator > "u" || navigator.onLine, Si = (e) => {
2939
+ let { errorBus: t } = N(e), [r, i] = c(xi), [o, l] = c(0), [u, d] = c(void 0), f = s(!0);
2909
2940
  a(() => (f.current = !0, () => {
2910
2941
  f.current = !1;
2911
2942
  }), []), a(() => {
@@ -2931,7 +2962,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2931
2962
  lastFailureAt: u,
2932
2963
  reportSuccess: p
2933
2964
  };
2934
- }, xi = "__voltro.connections.list", Si = "__voltro.connections.start", Ci = "__voltro.connections.submitToken", wi = "__voltro.connections.disconnect", Ti = {
2965
+ }, Ci = "__voltro.connections.list", wi = "__voltro.connections.start", Ti = "__voltro.connections.submitToken", Ei = "__voltro.connections.disconnect", Di = {
2935
2966
  connectionId: "",
2936
2967
  kind: "oauth2",
2937
2968
  label: "",
@@ -2942,14 +2973,14 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2942
2973
  expiresAt: null,
2943
2974
  lastError: null,
2944
2975
  connectedAt: null
2945
- }, Ei = (e, t) => {
2976
+ }, Oi = (e, t) => {
2946
2977
  if (t === "redirect") {
2947
2978
  globalThis.location.assign(e);
2948
2979
  return;
2949
2980
  }
2950
2981
  globalThis.open(e, "voltro-connect", "width=620,height=760,menubar=no,toolbar=no") === null && globalThis.location.assign(e);
2951
- }, Di = (e) => {
2952
- let { data: t } = V(e, xi, {}), r = q(e, Si), i = K(e, Ci), a = K(e, wi), o = t ?? [], s = r.pending || i.pending || a.pending, c = n((e) => ({
2982
+ }, ki = (e) => {
2983
+ let { data: t } = V(e, Ci, {}), r = q(e, wi), i = K(e, Ti), a = K(e, Ei), o = t ?? [], s = r.pending || i.pending || a.pending, c = n((e) => ({
2953
2984
  ...e,
2954
2985
  connected: e.status === "connected",
2955
2986
  needsAttention: e.status === "expired" || e.status === "revoked" || e.status === "error",
@@ -2957,7 +2988,7 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2957
2988
  connect: async (t) => {
2958
2989
  if (e.kind !== "oauth2") throw Error(`connection "${e.connectionId}" is a personal-access-token connection — call submitToken(token), not connect().`);
2959
2990
  let n = t?.redirectTo ?? `${globalThis.location.pathname}${globalThis.location.search}`;
2960
- Ei((await r.run({
2991
+ Oi((await r.run({
2961
2992
  connectionId: e.connectionId,
2962
2993
  redirectTo: n
2963
2994
  })).authorizeUrl, t?.mode);
@@ -2987,10 +3018,10 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
2987
3018
  get: l,
2988
3019
  pending: s
2989
3020
  };
2990
- }, Oi = (e, t) => {
2991
- let n = Di(e), r = n.get(t);
3021
+ }, Ai = (e, t) => {
3022
+ let n = ki(e), r = n.get(t);
2992
3023
  return o(() => r === void 0 ? {
2993
- ...Ti,
3024
+ ...Di,
2994
3025
  connectionId: t,
2995
3026
  label: t,
2996
3027
  connected: !1,
@@ -3015,6 +3046,6 @@ var $ = () => r(gr), vr = (e) => mr($().scopes, e), yr = (e) => hr($().scopes, e
3015
3046
  n.loading,
3016
3047
  n.pending
3017
3048
  ]);
3018
- }, ki = "framework-client";
3049
+ }, ji = "framework-client";
3019
3050
  //#endregion
3020
- export { pr as ADMIN_SCOPE, ki as CLIENT_NAME, xi as CONNECTIONS_LIST_TAG, wi as CONNECTION_DISCONNECT_TAG, Si as CONNECTION_START_TAG, Ci as CONNECTION_SUBMIT_TOKEN_TAG, _e as FrameworkRuntimesContext, Ae as FrameworkRuntimesProvider, he as LoadingSubscriptionCache, _r as PermissionProvider, ge as RpcErrorBus, me as SubscriptionCache, Nr as UNDO_APPLY_TAG, Mr as UNDO_LOG_TAG, Pr as UNDO_REDO_TAG, Se as _resetFrameworkRuntimesWarning, qt as applyPreloadSeeds, ft as applyStoreSeeds, we as buildApiRuntime, mr as canCall, hr as canCallAny, Ct as clearMutations, fi as clearSent, Ye as clearStoreHistory, _i as computeWindow, ai as createAnalytics, Vt as createHooks, Cr as decideAccess, ni as defineEvent, st as defineStore, Ir as defineTracking, ot as definedStores, Ar as deriveEntityAdmins, si as enqueueEntry, ii as eventCatalog, Yr as filtersFromSchema, jt as freshIdempotencyKey, Et as getMutationNotifier, xt as getMutations, P as isUnresolvedApi, Ht as makePreloadSeedBag, lt as makeStoreSeedBag, br as manifestUrl, di as markConflict, ui as markFailed, li as markSent, Tr as openAccessReason, dr as provenanceUrl, Gn as publishClientError, D as publishClientTrace, Yt as readPreloadedSeedOutcome, Jt as readPreloadedSnapshot, pi as replayable, qn as reportClientError, wr as requiredScopes, Xt as resetPreloadSeeds, ct as resetStoreRegistryForTests, Ie as resetStoreStorageForTest, B as resolveByTag, Fe as resolveStoreStorage, Lr as resolveTrackingEvent, Fn as resumableConsumeProgram, or as rowsToOptions, nn as runSequence, rr as schemaToColumns, Q as schemaToFields, Gt as seedPreloadedSubscription, Kt as seedPreloadedSubscriptionFailure, dt as seedStore, tn as sequence, Tt as setMutationNotifier, Ut as setPreloadSeedResolver, ut as setStoreSeedResolver, Pe as setStoreStorage, W as settleMutation, F as shallow, Ur as shallowArrayEqual, Wr as sourceValues, ye as ssrClientProxy, be as ssrStubHandle, O as stableKey, ke as startApiSupervisor, bt as startMutation, qe as storeHistory, Kn as subscribeClientErrors, re as subscribeClientTraces, St as subscribeMutations, Je as subscribeStoreHistory, oe as supersedesConfirmedPatches, Xe as travelToStoreState, Er as useAccessDecision, q as useAction, Vn as useAgent, Bn as useAgentChat, Pn as useAgentStream, ti as useAsyncValidation, vr as useCan, yr as useCanAny, xr as useCapabilityManifest, Oi as useConnection, bi as useConnectionStatus, Di as useConnections, Hn as useDataCopilot, lr as useDataTable, $r as useDebounced, Gr as useDerived, en as useEvent, ar as useFormBinding, Vr as useFormSkeleton, N as useFrameworkApi, Ce as useFrameworkRuntimes, K as useMutation, Jn as useOnRpcError, gi as useOutbox, $ as usePermissions, Zt as usePreloadedSubscription, oi as usePreview, fr as useProvenance, sr as useQueryField, Zr as useQueryFilters, Qr as useRecord, Un as useRefreshSubscriptions, Kr as useResourceCan, qr as useResourceCans, Ln as useResumableAgentStream, rn as useSequence, V as useSubscription, Hr as useTableSkeleton, Br as useTracking, jr as useUndo, Fr as useUndoLog, _n as useUpload, vi as useWindowedSubscription, vn as useWorkflow, En as useWorkflowDomainEvents, Dn as useWorkflowEventDeliveries, Tn as useWorkflowEvents, xn as useWorkflowRun, wn as useWorkflowRunEvents, Nn as useWorkflowRunState, Cn as useWorkflowRunSteps, Sn as useWorkflowRuns, yn as useWorkflowSignal, bn as useWorkflowUpdate, ri as validateEventPayload, ir as validateFields, ei as validationStatus, Mt as withIdempotencyKey, zr as wrapTrackedCallbacks };
3051
+ export { hr as ADMIN_SCOPE, ji as CLIENT_NAME, Ci as CONNECTIONS_LIST_TAG, Ei as CONNECTION_DISCONNECT_TAG, wi as CONNECTION_START_TAG, Ti as CONNECTION_SUBMIT_TOKEN_TAG, _e as FrameworkRuntimesContext, Ae as FrameworkRuntimesProvider, he as LoadingSubscriptionCache, yr as PermissionProvider, ge as RpcErrorBus, me as SubscriptionCache, Fr as UNDO_APPLY_TAG, Pr as UNDO_LOG_TAG, Ir as UNDO_REDO_TAG, Se as _resetFrameworkRuntimesWarning, qt as applyPreloadSeeds, ft as applyStoreSeeds, we as buildApiRuntime, gr as canCall, _r as canCallAny, Ct as clearMutations, mi as clearSent, Ye as clearStoreHistory, yi as computeWindow, si as createAnalytics, Vt as createHooks, Tr as decideAccess, ii as defineEvent, st as defineStore, Rr as defineTracking, ot as definedStores, Mr as deriveEntityAdmins, li as enqueueEntry, oi as eventCatalog, Zr as filtersFromSchema, jt as freshIdempotencyKey, Et as getMutationNotifier, xt as getMutations, Wn as isUnauthenticated, P as isUnresolvedApi, Ht as makePreloadSeedBag, lt as makeStoreSeedBag, Sr as manifestUrl, pi as markConflict, fi as markFailed, di as markSent, Dr as openAccessReason, pr as provenanceUrl, qn as publishClientError, D as publishClientTrace, Yt as readPreloadedSeedOutcome, Jt as readPreloadedSnapshot, hi as replayable, Yn as reportClientError, Er as requiredScopes, Xt as resetPreloadSeeds, ct as resetStoreRegistryForTests, Ie as resetStoreStorageForTest, B as resolveByTag, Fe as resolveStoreStorage, zr as resolveTrackingEvent, Fn as resumableConsumeProgram, cr as rowsToOptions, nn as runSequence, ar as schemaToColumns, Q as schemaToFields, Gt as seedPreloadedSubscription, Kt as seedPreloadedSubscriptionFailure, dt as seedStore, tn as sequence, Tt as setMutationNotifier, Ut as setPreloadSeedResolver, ut as setStoreSeedResolver, Pe as setStoreStorage, W as settleMutation, F as shallow, Gr as shallowArrayEqual, Kr as sourceValues, ye as ssrClientProxy, be as ssrStubHandle, O as stableKey, ke as startApiSupervisor, bt as startMutation, qe as storeHistory, Jn as subscribeClientErrors, re as subscribeClientTraces, St as subscribeMutations, Je as subscribeStoreHistory, oe as supersedesConfirmedPatches, Xe as travelToStoreState, Or as useAccessDecision, q as useAction, Vn as useAgent, Bn as useAgentChat, Pn as useAgentStream, ri as useAsyncValidation, br as useCan, xr as useCanAny, Cr as useCapabilityManifest, Ai as useConnection, Si as useConnectionStatus, ki as useConnections, Hn as useDataCopilot, dr as useDataTable, ti as useDebounced, qr as useDerived, en as useEvent, sr as useFormBinding, Ur as useFormSkeleton, N as useFrameworkApi, Ce as useFrameworkRuntimes, K as useMutation, Xn as useOnRpcError, vi as useOutbox, $ as usePermissions, Zt as usePreloadedSubscription, ci as usePreview, mr as useProvenance, lr as useQueryField, $r as useQueryFilters, ei as useRecord, Un as useRefreshSubscriptions, Jr as useResourceCan, Yr as useResourceCans, Ln as useResumableAgentStream, rn as useSequence, V as useSubscription, Wr as useTableSkeleton, Hr as useTracking, Nr as useUndo, Lr as useUndoLog, _n as useUpload, bi as useWindowedSubscription, vn as useWorkflow, En as useWorkflowDomainEvents, Dn as useWorkflowEventDeliveries, Tn as useWorkflowEvents, xn as useWorkflowRun, wn as useWorkflowRunEvents, Nn as useWorkflowRunState, Cn as useWorkflowRunSteps, Sn as useWorkflowRuns, yn as useWorkflowSignal, bn as useWorkflowUpdate, ai as validateEventPayload, or as validateFields, ni as validationStatus, Gn as wireAuthRefresh, Mt as withIdempotencyKey, Vr as wrapTrackedCallbacks };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/client",
3
- "version": "0.39.1",
3
+ "version": "0.41.0",
4
4
  "description": "Framework-agnostic client bindings — the typed RpcClient, subscription cache, and reactive data layer the web hooks build on.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -33,7 +33,7 @@
33
33
  "node": ">=24.0.0"
34
34
  },
35
35
  "dependencies": {
36
- "@voltro/protocol": "0.39.1"
36
+ "@voltro/protocol": "0.41.0"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@effect/platform": "^0.97.0",