@voltro/protocol 0.42.0 → 0.43.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,166 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.43.1] — 2026-08-18
43
+
44
+ ### Fixed
45
+
46
+ - **@voltro/database** — A write recorder that fails inside someone's transaction now says which recorder, on which write, and what the database actually said.
47
+
48
+ `@effect/sql` renders every driver failure as `SqlError: Failed to execute statement` — one sentence that fits a missing column, a dangling foreign key, an over-long value and a duplicate key equally. The driver's own words hang off a SYMBOL on a `FiberFailure`, so a caller who reaches for `.cause` gets `undefined` and concludes there is nothing there.
49
+
50
+ That is expensive precisely where recorders run: the caller's write was ordinary, and what failed was framework machinery one table over. The message now reads
51
+
52
+ ```
53
+ write recorder '_voltro_row_history' failed while recording an update on 'users':
54
+ Duplicate entry 'rowver_…' for key 'PRIMARY' [code=ER_DUP_ENTRY errno=1062 …]
55
+ ```
56
+
57
+ and the original error is kept as `cause` for anyone who does walk the chain. The failure still takes the transaction down — that is the guarantee and it is unchanged.
58
+
59
+ `describeDriverError` (`@voltro/database`) is the shared summariser, built on the existing cause extractor rather than a second walker. It returns nothing when the chain carries nothing driver-shaped, so an ordinary programming error from a recorder arrives as itself instead of wrapped in prose about a database.
60
+ - **@voltro/database** — On MariaDB, a `varchar` column could introspect as `json` because a DIFFERENT table had a json column with the same column name.
61
+
62
+ MariaDB names a column-level CHECK after the COLUMN, and those names are unique per table, not per schema. `information_schema.check_constraints` on MySQL has no `TABLE_NAME`, so the introspector recovered it by joining `table_constraints` on `(schema, constraint_name)` — which on MariaDB cross-products every same-named check across every table. Measured on 11.8:
63
+
64
+ ```
65
+ a.payload LONGTEXT CHECK (json_valid(`payload`))
66
+ b.payload VARCHAR(255) CHECK (`payload` in ('x','y'))
67
+
68
+ join result: a → json_valid, a → in(…), b → json_valid, b → in(…)
69
+ ```
70
+
71
+ So `b.payload` reads as `json`, and `a.payload` picks up an enum it does not have. Downstream that is not a cosmetic label: the planner emits a blocked `alter-column-type` with `from: 'json'` that no `.narrowedFrom()` can honestly acknowledge, because the premise is false — and since the data-transfer manifest records introspected types, the same misreading travels into the bundle and reappears as schema drift on import.
72
+
73
+ MariaDB's own `check_constraints` HAS `TABLE_NAME`. The introspector asks for it directly now and keeps the join as the MySQL path, where check-constraint names are schema-unique and the join is sound. That asymmetry is why a single-engine test could not see this: the wrong query passes on MySQL.
74
+ - **@voltro/database** — `voltro db apply` could not drop a CHECK constraint on the mysql family at all, and each of the three reasons hid the next.
75
+
76
+ **1. `DROP CHECK` is MySQL-8 syntax.** MariaDB has never had it — measured on 11.8, `ALTER TABLE t DROP CHECK c` is `ERROR 1064`, while `DROP CONSTRAINT c` works on both engines. A plan containing a `drop-check` therefore died on the first one, on a family whose migrations are NOT atomic: the run stopped with the earlier statements committed and no rollback.
77
+
78
+ **2. The name was assumed, not read.** The applier dropped `<table>_<column>_check` — which is only what its own `add-check` would have named it. A CHECK created at table bring-up is INLINE and UNNAMED, so the server names it (`CONSTRAINT_1` / `<table>_chk_1` / the column name). Dropping a name that does not exist reports "does not exist", which is indistinguishable from the "already gone" a resume legitimately produces — so the statement succeeded, the constraint stayed, and the plan re-proposed the identical `drop-check` forever. The name comes from the catalog now.
79
+
80
+ **3. A column-level CHECK cannot be dropped by name on MariaDB at all.** Measured: the catalog lists it under the column's name, `DROP CONSTRAINT` on that name answers 1091, and only redefining the column removes it. The applier now drops by catalog name, ASKS whether the constraint survived, and redefines the column when it did — so a rebuild happens only in the case that needs one.
81
+
82
+ **And the same investigation closed the MySQL `.oneOf()` round-trip gap.** `parseEnumCheck` was documented as handling MySQL's rendering and did not: MySQL backslash-escapes the string DELIMITERS (`_utf8mb4\'draft\'`), and the parser rewrote those to the SQL doubling `''` — which is how a quote INSIDE a value is written. Every delimiter became escaped content, every value came back empty, and the filter dropped them. `.oneOf()` now round-trips on MySQL, and the suite that asserted the gap as a known one asserts the round-trip instead.
83
+
84
+ Plus, on a failed apply: the error now states how many operations were already applied and whether this dialect rolls back. The ledger held that number; it never reached the operator, who had to re-plan and diff the counts to learn how far the run got.
85
+ - **@voltro/plugin-versioning** — `versioningPlugin({ timing: 'in-transaction' })` built its history row's primary key from `(rowId, version)` while the version counter three lines above was scoped to `(tableName, rowId)`. Two versioned tables carrying the same row id therefore collided — permanently.
86
+
87
+ The shape is not exotic: `actors.id === users.id` is what the framework's own audit trail asks for, an `actors` row whose id is the user's so an audited write satisfies `createdBy → actors`. In an app that follows it, every user row has a twin.
88
+
89
+ The collision does not heal, and that is what turns a duplicate into an outage. The second table's insert fails, so its history row is never written, so `maxOf` for that table stays `null`, so the next attempt computes the same version and the same id. Every write to that row is dead from then on — surfacing as `ER_DUP_ENTRY` on an ordinary `store.update`, naming a row id in a table the caller never wrote to.
90
+
91
+ The key is `(table, rowId, version)` now — the same shape the post-commit path always built. It stays deterministic (no clock, no process-local counter), which is what lets it survive a replica restart; it just carries every part of the key it claims to be unique over.
92
+
93
+ **No cleanup is needed for rows already written.** They keep their old ids and belong to whichever table wrote them; the new keys cannot collide with them, and `byRow` is not unique. An app blocked by this is unblocked by the upgrade alone.
94
+
95
+ Covered twice: the recorder against a port that refuses duplicates (the mechanism, including that a repeat does not settle), and two versioned tables sharing an id against live postgres (the real primary key, inside the caller's transaction). The suite that existed exercised ONE table, which cannot produce a collision at all — and read exactly like a suite that covered this.
96
+
97
+ ### Internal (no consumer-facing effect)
98
+
99
+ - **@voltro/sql-mysql** — Two test-only defects in `sql-mysql`, both found by a release gate, both of the same family: a check that could not fail, and a failure reported in the wrong place. No product code changed.
100
+
101
+ **An assertion that could not fail.** `dropCheckSyntax.integration.test.ts` fell back to a HAND-BUILT plan when the planner produced no operations — and the fabricated operation was a `drop-check`, which is exactly what the next line asserts the plan contains. So an engine whose planner stopped emitting it would have been handed one and reported green. The fallback is deleted; both engines produce the operation now, which is what this release fixed, and the assertion is load-bearing again (4/4 on mysql AND mariadb without it).
102
+
103
+ It surfaced as a TYPE error rather than a false pass, because the fallback's object widened `plan` into a union `applyPlan` does not accept. Worth noting which check caught it: `vitest` transpiles without type-checking, so the suite was green and only `tsc` objected — the gate's `typecheck` and `lint` steps are what went red.
104
+
105
+ **A wait that gave up in silence.** `waitFor` in both binlog CDC suites looped to a deadline and then RETURNED, so a "prove the reader is live" wait that expired let the test carry on, kill the binlog dump thread, and fail twenty lines later on `expect(ids).toContain('todo_wd_before')` — an assertion about a different claim, in a different place. It throws now, naming the wait and the window, and all twelve call sites carry a label.
106
+
107
+ The window is named too: `FIRST_ATTACH_MS = 30_000`, up from 12 s. The reasoning is the 40 s window already in the same file, whose comment says a re-attach plus binlog catch-up takes longer under a loaded full-suite run — a FIRST attach does both and only skips the backoff, so 12 s beside 40 s was an asymmetry the file's own reasoning did not support. That is an argument from the neighbouring comment, not a measurement; if it expires again, `waitFor` now says which wait and for how long, and that number is the one to argue with rather than raising this one twice.
108
+
109
+ ---
110
+
111
+ ## [0.43.0] — 2026-08-18
112
+
113
+ ### ⚠ BREAKING
114
+
115
+ - **@voltro/data-transfer, @voltro/cli** — `DanglingReferenceError` is now `RowsRefusedError`, and it separates the rows that failed from the rows that failed because those rows did.
116
+
117
+ **The name.** The import raised it for EVERY row still refused after deferred-FK resolution, whatever the reason — a NOT NULL violation, a duplicate key, a value the database computes for itself. The tag named ONE possible cause and put it where a reader looks first, so any other refusal arrived mislabelled. The new name states the outcome; each row's `reason` states the cause, which is where a cause can honestly be claimed.
118
+
119
+ **The split.** A row is `derived` when one of its reference columns holds the primary key of another row that also failed in this run: it could not have landed whatever it contained, so its reason describes the parent's problem. The relation is transitive, decided from the DATA (the failed ids against the reference-typed values), so no schema knowledge is needed. `primaryCount` is the number an operator acts on, `rows` lists primary failures FIRST so the cap never spends its budget on consequences, and the CLI leads with both numbers:
120
+
121
+ ```
122
+ import refused 300 row(s), of which 1 are the actual failures — the rest could
123
+ not land because a row they reference did not.
124
+ teams t1 foreign key teams_ibfk_1: the referenced row does not exist [1452]
125
+ … and 299 row(s) behind them. Fix the 1 above and re-run; they resolve with
126
+ their parents.
127
+ ```
128
+
129
+ In an FK-dense bundle one refused parent takes its whole subtree with it, so the length of a flat list says how connected the data is, not how many problems there are — and the single row that explains all of them sits somewhere in the middle of it.
130
+
131
+ The codemod rewrites the import and every use of the symbol. It does NOT rewrite a tag STRING (`Effect.catchTag('DanglingReferenceError', …)`, `err._tag === '…'`) — change those to `'RowsRefusedError'` — and the payload gained `primaryCount` plus a `derived` flag per row.
132
+
133
+ ### Fixed
134
+
135
+ - **@voltro/cli** — `voltro doctor`'s `subject-write-no-guard` rule reads the DESCRIPTOR before it reports. It looked only at the executor, and the access decision is not declared there.
136
+
137
+ Every form of access decision the framework has — `internal: true`, `guards: [...]`, `openAccess:` — is declared on the DESCRIPTOR. So an app that declares them properly got a finding for each one, and on a codebase whose procedures are mostly `internal: true` the rule fires on essentially all of them and is wrong essentially every time.
138
+
139
+ That is worse than a rule that finds nothing: it is the longest line in the report and it reads like a security finding, so it teaches the reader to skim the place a real finding would have appeared.
140
+
141
+ The premise was structurally impossible for most of them, and the framework says so itself: `security.defaultDeny` refuses at boot any wire-exposed procedure declaring neither `guards:` nor `openAccess:`. So "an anonymous caller reaches the write" can only be true of an `openAccess` procedure. That is what the rule looks for now — plus the handler check it always honoured, plus an ownership comparison against `subject.id`, which is the refusal the rule says is missing. Where no descriptor can be read, it says nothing: the claim is about a declaration, and a finding whose evidence was never opened is the failure mode this fixes.
142
+
143
+ The `use:` line changed with it. It recommended `.guard(requireScope('…'))`; the shipped guide teaches declarative `guards:` and calls a hand-written per-executor scope check the thing `guards:` exists to delete. A rule may not recommend the shape the guide argues against.
144
+ - **@voltro/database, @voltro/data-transfer** — A `voltro data` transfer no longer carries GENERATED column values, and no longer loses every row that has one.
145
+
146
+ The export wrote the computed values into the bundle and the import sent them back in the `INSERT` column list. MariaDB refuses that for any value except NULL (`1906: The value specified for generated column 'x' in table 't' has been ignored`); postgres refuses a non-DEFAULT value outright. So the transfer failed per ROW, not per table, and only for the rows whose generated value was non-NULL.
147
+
148
+ That selectivity is the dangerous part. `.uniqueActive()` lowers to exactly such a column on mysql/mariadb — a STORED generated column holding the key while the row is live and NULL once it is soft-deleted — so the refused rows are the LIVE ones and the accepted ones are the tombstones. A table can come out looking like "a few rows failed" or empty, depending only on how many of its rows are deleted, and any table with a foreign key into it fails behind it.
149
+
150
+ Both ends are fixed from one source of truth: **introspection now reports generated columns on every dialect** (`generatedAs`, from `information_schema.generation_expression` on mysql/mariadb, `is_generated` on postgres, `PRAGMA table_xinfo`'s hidden flag on sqlite, `sys.computed_columns` on mssql). It was declared-side only before — invisible to the planner, which does not compare it, and load-bearing for anything that writes rows back.
151
+
152
+ The exporter omits those columns, values and all. The importer strips them from every incoming row using the TARGET's snapshot, because a bundle already written still carries them and a file on disk is data, read where it is.
153
+
154
+ **`voltro serve`'s admin export/import needed a second fix, and without it this one reached only the direct transport.** The running instance hands those handlers `declaredSnapshot(tables)` — no dialect — and `.uniqueActive()` lowers to a generated column only when the snapshot knows the engine. So over `--target api` the snapshot described a schema with no generated columns while the database had several, and the export wrote their values back into the bundle exactly as before. It passes the dialect now (the variable was already on the next line).
155
+
156
+ `generatedAs` is also kept OUT of the schema fingerprint. Introspection can read the fact back but not a comparable value — the engine returns its own normalisation of the expression, never the declared spelling — so hashing it would make declared and live disagree permanently: a schema nobody touched reporting a changed declaration on every boot, and a transfer target that matches its bundle exactly refused as drifted.
157
+
158
+ Covered by a live mariadb→mariadb and mysql→mysql round trip over a `.uniqueActive()` table with live and soft-deleted rows, asserting the target recomputed the value rather than that the row merely arrived.
159
+ - **@voltro/sql-mysql** — On mysql/mariadb, a write REJECTED by the database through `insertIgnore` was reported as a conflict when the caller was not inside a transaction — and never reached the caller as a typed `ConstraintViolation` at all.
160
+
161
+ Two causes, both measured against live MySQL 8.4 and MariaDB 11.
162
+
163
+ **The connection.** `INSERT IGNORE` demotes every error to a warning, so the store reads `SHOW WARNINGS` to tell a rejection from a conflict. That describes the last statement on a CONNECTION, and outside a transaction every statement acquires its own from the pool — so the read was unattributable and came back empty. The rejected write then surfaced as "the insert was skipped as a conflict, but no existing row matches conflictColumns […] the constraint that fired is unknown", whose enumeration lists only conflict causes. A rejection described as a conflict is the exact sentence this path was fixed once already for producing; it survived on the path that had no transaction to read on. The store now pins one connection for the whole decision — the same pinning `insertRecoverAutoId` does for `LAST_INSERT_ID()`.
164
+
165
+ **The classification.** The store swallowed the driver's error and raised a prose one of its own, so `classifyConstraintViolation` had nothing to read: this was the one write path where the typed error could not fire, while every other one produced it. The warning IS the driver's payload — `INSERT IGNORE` only changed how it was delivered — so it is handed on in the shape the driver would have thrown. A rejection now arrives as the same `ConstraintViolation { kind: 'foreignKey', … }` a plain `insert` produces. Nothing new crosses the wire: the classifier extracts the constraint NAME as a delimited group, never the sentence.
166
+
167
+ This is the default `voltro data import` path (`--mode append`, `--on-conflict skip`, without `--atomic`), so a row rejected by a foreign key was reported to the operator as a conflict with an unknown cause.
168
+
169
+ `constraintViolation.integration.test.ts` now asserts the `insertIgnore` seam per dialect against live postgres 17, MySQL 8.4, MariaDB 11 and SQL Server 2022. It was the missing assertion behind a claim derived from the wiring — the classification does sit on all ten write paths, which is not the same as a classifiable error arriving on all ten.
170
+ - **@voltro/protocol, @voltro/runtime** — The framework's store errors — `ConstraintViolation`, `TenantScopeViolation`, `TenantRowNotFound`, `ServerOnlyColumnWrite`, `TableValidationFailed`, `StoreOperationFailed` — are exported from `@voltro/protocol` and can therefore be declared in a descriptor's `error:` union. They could not be.
171
+
172
+ They lived in `@voltro/runtime`, which reaches `node:child_process`, `node:http` and `node:crypto`. A descriptor is loaded VALUE-LEVEL by the web client (the `RpcClient` needs every procedure's Schema), so a descriptor importing from there is refused at boot by the browser-safety guard — correctly. The typed half of these errors was therefore unreachable: the docs told you to declare them, and the boot said no.
173
+
174
+ What that leaves is the untyped half only. The error still arrives as an `InternalError` carrying a readable sentence, so telling `foreignKey` ("the row you picked is gone") from `foreignKeyInUse` ("this row is still referenced") — two different messages for the user — means parsing that sentence. Over a set of generated delete mutations that is a string comparison per procedure, which is the thing the typed error exists to delete.
175
+
176
+ `@voltro/runtime` re-exports all six, so server code is unchanged. The classes have no server dependency of any kind — the file imports `Schema` from `effect` and nothing else, and `browserSafetyGuard.test.ts` now pins a descriptor that declares one, so moving them back reads as a boot failure rather than as a passing rename.
177
+ - **@voltro/database, @voltro/sql-mysql** — A blocked `alter-column-type` told every dialect to write a postgres cast.
178
+
179
+ The refusal is correct — a bare type change may not be value-preserving, so it is refused until acknowledged. Its `fix:` line was not:
180
+
181
+ ```
182
+ acknowledge it on the column: `.narrowedFrom('json', { using: 'meta::text' })`
183
+ ```
184
+
185
+ `USING <expr>` is postgres syntax and a postgres capability. The mysql arm of the applier emits `MODIFY COLUMN`, the mssql arm `ALTER COLUMN`, and sqlite rebuilds the table — none of them can carry a cast expression and none of them reads `using`. So an operator on any other engine was handed a line to paste into their schema containing syntax their database has never seen, inside an argument that is discarded. A refusal is read as an instruction, and the more carefully it is read the more thoroughly a wrong one is followed.
186
+
187
+ The fix line is dialect-aware now: postgres keeps the `using` half, everything else gets `.narrowedFrom('<type>')` plus the fact that the engine converts in place — because a refusal that offers no expressible fix reads as "the framework cannot do this at all".
188
+
189
+ Covered on live MySQL and MariaDB by both halves at once: what the refusal SAYS, and that following it applies AND converges with the row intact. A message test alone would keep passing over a broken apply; a convergence test alone is what let the wrong message survive this long.
190
+
191
+ Also on the same path: `upsert` with a PARTIAL row (one omitting a NOT NULL column that has no default) failed on MariaDB and succeeded on MySQL. The native `INSERT … ON DUPLICATE KEY UPDATE` validates its insert half even when only the update half runs, so the row was rejected although the target existed and only needed patching. A partial row takes the lookup path on both engines now; the single-statement form still covers the complete-row case, which is what a data transfer and every generated CRUD write send.
192
+ - **@voltro/sql-mysql** — On MariaDB, `upsert` could write a DIFFERENT row than the one it was given and report success.
193
+
194
+ `INSERT … ON DUPLICATE KEY UPDATE` fires on ANY unique key, not on the one named in `conflictColumns`. So an incoming row whose (say) `email` already belonged to a different primary key updated THAT row instead — and since `id` is excluded from the SET list, the row the caller handed over was never written. Measured on a live server: the call returned a row, the target kept the old id, the new row was absent, and the existing row had silently taken the incoming values. A bulk transfer on top of that prints `import complete` over missing data, which is the worst failure shape available: there is nothing to investigate.
195
+
196
+ The two engines of the family disagreed here, which is part of why it survived. The non-RETURNING path (MySQL) looks the row up by `conflictColumns` first, does not find it, and lets the INSERT fail with a duplicate-key error. Loud was always right.
197
+
198
+ Both refuse now, with a message naming both ids and the fact that the collision was on a constraint other than the one named. The check runs inside a transaction — a short one of the store's own when the caller is not already in one — so the wrong row is rolled back rather than reported after the fact: detecting this afterwards still leaves someone else's row overwritten.
199
+
200
+ ---
201
+
42
202
  ## [0.42.0] — 2026-08-17
43
203
 
44
204
  ### ⚠ BREAKING
package/dist/apikey.d.ts CHANGED
@@ -205,7 +205,7 @@ declare const Subject: Schema.Union<[Schema.Struct<{
205
205
  * Set when this caller PRESENTED a credential and it was rejected — an
206
206
  * expired token above all. Absent when they presented none.
207
207
  *
208
- * The two are the same Subject and must not be the same ANSWER. A consumer
208
+ * The two are the same Subject and must not be the same ANSWER. A deployment
209
209
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
210
210
  * strategy logged `supabase jwt expired`, the caller fell through to
211
211
  * anonymous, and the guard then refused with `missing required scope
package/dist/index.d.ts CHANGED
@@ -1049,6 +1049,64 @@ export declare const connectionSubmitTokenDescriptor: MutationProcedureDescripto
1049
1049
  ok: typeof Schema.Boolean;
1050
1050
  }>, Schema.Union<[typeof ConnectionNotDeclared, typeof ConnectionSubjectRequired, typeof ConnectionKindMismatch, typeof ConnectionHandshakeFailed]>>;
1051
1051
 
1052
+ /**
1053
+ * The database refused a write because it broke an integrity rule the SCHEMA
1054
+ * declares — a foreign key, a unique index, a NOT NULL, a CHECK.
1055
+ *
1056
+ * **Why this is typed at all.** Without it the driver failure is a `SqlError`,
1057
+ * which the rpc layer collapses to a bare `InternalError` on purpose (a
1058
+ * `SqlError`'s text is not safe to forward — see below). The caller then gets
1059
+ * "something went wrong" for a failure that is entirely about the input it just
1060
+ * sent, and the only way to find out which rule fired is to re-run the
1061
+ * statement by hand against the database. That is a real reported shape:
1062
+ * that.
1063
+ *
1064
+ * **Why it carries names and not the driver's sentence.** The temptation is to
1065
+ * forward `cause.message`, and it is measured to be wrong: postgres attaches
1066
+ * `Failing row contains (…)` — the complete row, every column — to a not-null
1067
+ * and a check violation; mysql and mssql echo the duplicate VALUE on a unique
1068
+ * violation. A constraint or column NAME is schema, which this framework
1069
+ * already puts on the wire (`TableValidationFailed.table`). A row is data, and
1070
+ * the caller who provoked the error is not automatically entitled to it.
1071
+ *
1072
+ * **Not every dialect can fill every field.** sqlite reports a foreign-key
1073
+ * failure as the bare sentence `FOREIGN KEY constraint failed` — no name, no
1074
+ * column, no direction — so `constraint` is absent there and the direction is
1075
+ * inferred from the operation. `kind` is the field that is always right.
1076
+ */
1077
+ export declare class ConstraintViolation extends ConstraintViolation_base {
1078
+ /**
1079
+ * A sentence built from the fields above and nothing else.
1080
+ *
1081
+ * It exists because an undeclared tagged error reaches the client through
1082
+ * `defectMessage`, which renders `String(error)` — and a `Schema.TaggedError`
1083
+ * with no `message` renders as `[object Object]`. Without this getter the
1084
+ * caller would get a correctly-typed error carrying no information, which is
1085
+ * the same dead end in a different shape.
1086
+ */
1087
+ get message(): string;
1088
+ }
1089
+
1090
+ declare const ConstraintViolation_base: Schema.TaggedErrorClass<ConstraintViolation, "ConstraintViolation", {
1091
+ readonly _tag: Schema.tag<"ConstraintViolation">;
1092
+ } & {
1093
+ /**
1094
+ * Which rule fired. `foreignKey` = the row you referenced does not exist;
1095
+ * `foreignKeyInUse` = this row may not go, others still reference it. They
1096
+ * are opposite situations with opposite fixes, so a UI branches on them
1097
+ * separately.
1098
+ */
1099
+ kind: Schema.Literal<["foreignKey", "foreignKeyInUse", "unique", "notNull", "check"]>;
1100
+ /** The table the write targeted — the framework's own name for it, not the driver's. */
1101
+ table: typeof Schema.String;
1102
+ /** Which store op was attempted: 'insert' | 'update' | 'delete' | …. */
1103
+ operation: typeof Schema.String;
1104
+ /** The constraint / index name, when the dialect names one. */
1105
+ constraint: Schema.optional<typeof Schema.String>;
1106
+ /** The column, when the dialect names one instead of (or beside) a constraint. */
1107
+ column: Schema.optional<typeof Schema.String>;
1108
+ }>;
1109
+
1052
1110
  /**
1053
1111
  * A handle to a cluster-coordinated periodic task the plugin armed via
1054
1112
  * `PluginBindContext.scheduleCoordinated`. Keep it to `stop()` the task
@@ -1312,7 +1370,7 @@ export declare const defineEvent: <const Name extends string, Key extends Schema
1312
1370
  * `'latest'` — a newer delivery supersedes a pending one; a slow subscriber
1313
1371
  * gets the current value and is told nothing, because nothing was lost.
1314
1372
  *
1315
- * See {@link EventDeliverySemantics}. The test is "would a consumer be wrong
1373
+ * See {@link EventDeliverySemantics}. The test is "would a deployment be wrong
1316
1374
  * to miss one?" — not "is this event frequent?".
1317
1375
  */
1318
1376
  readonly delivery?: EventDeliverySemantics;
@@ -1672,7 +1730,7 @@ export declare const eventAttached: Schema.Struct<{
1672
1730
  * reach a state it could have had immediately, and report a "loss" that was
1673
1731
  * never a loss.
1674
1732
  *
1675
- * The honest test: **would a consumer be wrong to miss one?** If the next value
1733
+ * The honest test: **would a deployment be wrong to miss one?** If the next value
1676
1734
  * supersedes it, that is `'latest'` — and it is probably state rather than an
1677
1735
  * event at all.
1678
1736
  */
@@ -2025,7 +2083,7 @@ export declare interface GuardSpec<Input = unknown> {
2025
2083
  * in its own tables (a `teamMembers` row, say) registers its own tuple source
2026
2084
  * rather than copying data across; see `policyGuardResolver.ts`.
2027
2085
  *
2028
- * That paragraph is here because its absence cost a consumer their access
2086
+ * That paragraph is here because its absence cost a deployment their access
2029
2087
  * gate. This comment used to describe the resolver as "a future ReBAC /
2030
2088
  * `accessPolicy()` resolver" — written before the ReBAC path shipped and
2031
2089
  * never updated. They read the type, quoted the sentence, concluded there was
@@ -3528,7 +3586,7 @@ export declare interface QueryCacheConfig {
3528
3586
  *
3529
3587
  * `'tenant'` exists because the other two were the only options and neither
3530
3588
  * fits an org-wide figure: `subject` recomputes it per person, and `global`
3531
- * is not a cache but a cross-tenant leak. A consumer reported computing the
3589
+ * is not a cache but a cross-tenant leak. A deployment reported computing the
3532
3590
  * same nine-table statistic up to 18 times for 18 employees rather than take
3533
3591
  * the second option, which was the correct call.
3534
3592
  *
@@ -4028,6 +4086,33 @@ declare type ServerErrorListener = (event: ServerErrorEvent) => void;
4028
4086
 
4029
4087
  export declare type ServerErrorSource = 'rest' | 'aggregate' | 'subscriber' | 'reaction' | 'schedule' | 'workflow' | 'webhook' | 'startup';
4030
4088
 
4089
+ /**
4090
+ * A generated CRUD write (`crud.create` / `crud.update`) was handed a
4091
+ * `.serverOnly()` column in its INPUT.
4092
+ *
4093
+ * `.serverOnly()` is the WIRE-exposure axis: the column never crosses the
4094
+ * boundary in EITHER direction. Reads strip it; a write that accepts it is the
4095
+ * same violation mirrored — mass assignment of a column the schema declared the
4096
+ * client may not see, let alone set.
4097
+ *
4098
+ * Refused rather than silently stripped: a stripped field makes an attack
4099
+ * indistinguishable from a no-op and leaves an honest caller wondering why the
4100
+ * value it sent never landed. `columns` names what was rejected so the fix
4101
+ * (drop the field from the descriptor's input schema, or from the caller) is
4102
+ * mechanical.
4103
+ */
4104
+ export declare class ServerOnlyColumnWrite extends ServerOnlyColumnWrite_base {
4105
+ }
4106
+
4107
+ declare const ServerOnlyColumnWrite_base: Schema.TaggedErrorClass<ServerOnlyColumnWrite, "ServerOnlyColumnWrite", {
4108
+ readonly _tag: Schema.tag<"ServerOnlyColumnWrite">;
4109
+ } & {
4110
+ /** The table the write targeted. */
4111
+ table: typeof Schema.String;
4112
+ /** The `.serverOnly()` columns the input tried to set. */
4113
+ columns: Schema.Array$<typeof Schema.String>;
4114
+ }>;
4115
+
4031
4116
  /**
4032
4117
  * Publish the caller's fully-resolved scope set for this request (raw subject
4033
4118
  * scopes ∪ role-derived scopes ∪ any extra grants). Called by the rbac
@@ -4058,6 +4143,33 @@ export declare const setResourceScopeResolver: (resolver: ResourceScopeResolver
4058
4143
  */
4059
4144
  export declare const sourceKeys: (source: ReactivitySource | ReadonlyArray<ReactivitySource> | undefined) => ReadonlyArray<string>;
4060
4145
 
4146
+ /**
4147
+ * Discriminated union of all framework-owned store errors. Use it on
4148
+ * a mutation's `error:` schema when you want every kind surfaced
4149
+ * typed to the client.
4150
+ */
4151
+ export declare type StoreError = TenantScopeViolation | TenantRowNotFound | ServerOnlyColumnWrite | StoreOperationFailed | TableValidationFailed | ConstraintViolation;
4152
+
4153
+ /**
4154
+ * Anything else the underlying `DataStore` raised during a write or
4155
+ * query. `cause` is the stringified original error — sufficient for
4156
+ * logs + UI, doesn't try to serialise complex error chains across the
4157
+ * rpc boundary. The `_tag` discriminator stays cheap to pattern-match.
4158
+ */
4159
+ export declare class StoreOperationFailed extends StoreOperationFailed_base {
4160
+ }
4161
+
4162
+ declare const StoreOperationFailed_base: Schema.TaggedErrorClass<StoreOperationFailed, "StoreOperationFailed", {
4163
+ readonly _tag: Schema.tag<"StoreOperationFailed">;
4164
+ } & {
4165
+ /** Which DataStore op was attempted: 'query' | 'insert' | 'update' | 'delete' | 'hardDelete'. */
4166
+ operation: typeof Schema.String;
4167
+ /** The table the op targeted. */
4168
+ table: typeof Schema.String;
4169
+ /** `String(originalError)` — round-trip-safe diagnostic form. */
4170
+ cause: typeof Schema.String;
4171
+ }>;
4172
+
4061
4173
  export declare type StrategyResolution = {
4062
4174
  readonly kind: 'matched';
4063
4175
  readonly subject: Subject;
@@ -4156,7 +4268,7 @@ export declare const Subject: Schema.Union<[Schema.Struct<{
4156
4268
  * Set when this caller PRESENTED a credential and it was rejected — an
4157
4269
  * expired token above all. Absent when they presented none.
4158
4270
  *
4159
- * The two are the same Subject and must not be the same ANSWER. A consumer
4271
+ * The two are the same Subject and must not be the same ANSWER. A deployment
4160
4272
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
4161
4273
  * strategy logged `supabase jwt expired`, the caller fell through to
4162
4274
  * anonymous, and the guard then refused with `missing required scope
@@ -4202,7 +4314,7 @@ export declare const SubjectIdentity: Schema.Union<[Schema.Struct<{
4202
4314
  * Set when this caller PRESENTED a credential and it was rejected — an
4203
4315
  * expired token above all. Absent when they presented none.
4204
4316
  *
4205
- * The two are the same Subject and must not be the same ANSWER. A consumer
4317
+ * The two are the same Subject and must not be the same ANSWER. A deployment
4206
4318
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
4207
4319
  * strategy logged `supabase jwt expired`, the caller fell through to
4208
4320
  * anonymous, and the guard then refused with `missing required scope
@@ -4360,10 +4472,70 @@ export declare const subscriptionEvent: <D extends Schema.Schema.Any>(data: D) =
4360
4472
 
4361
4473
  export declare const systemSubject: (id: string, scopes?: ReadonlyArray<string>) => Subject;
4362
4474
 
4475
+ /**
4476
+ * Pre-INSERT row validation against a table's `.validate(Schema)`
4477
+ * decoder failed. The MutationStore runs the table's `insertSchema`
4478
+ * AFTER defaults + computed + audit/tenant stamps; failure means
4479
+ * the stamped row didn't satisfy the decoder. `issues` is the
4480
+ * formatted ArrayFormatter output (cheap to render in UI, doesn't
4481
+ * leak the original Schema instance).
4482
+ */
4483
+ export declare class TableValidationFailed extends TableValidationFailed_base {
4484
+ }
4485
+
4486
+ declare const TableValidationFailed_base: Schema.TaggedErrorClass<TableValidationFailed, "TableValidationFailed", {
4487
+ readonly _tag: Schema.tag<"TableValidationFailed">;
4488
+ } & {
4489
+ /** The table the row targeted. */
4490
+ table: typeof Schema.String;
4491
+ /** Top-level explanation for logs + UI ("user.email failed pattern check"). */
4492
+ summary: typeof Schema.String;
4493
+ /** Flat list of `{ path, message }` per failing leaf. Path uses dot-notation. */
4494
+ issues: Schema.Array$<Schema.Struct<{
4495
+ path: typeof Schema.String;
4496
+ message: typeof Schema.String;
4497
+ }>>;
4498
+ }>;
4499
+
4363
4500
  export declare type Target<Input = unknown, Row = unknown> = TargetSpec<Input, Row> | ReadonlyArray<TargetSpec<Input, Row>>;
4364
4501
 
4365
4502
  export declare type TargetSpec<Input = unknown, Row = unknown> = InsertTarget<Input, Row> | UpdateTarget<Input, Row> | DeleteTarget<Input>;
4366
4503
 
4504
+ /**
4505
+ * A keyed-by-primary-key write (`ctx.store.update(table, id, patch)`,
4506
+ * `delete(table, id)`, `hardDelete(table, id)`, `patchJson(table, id, …)`) on a
4507
+ * `tenant()`-scoped table did not resolve to a row inside the CALLER's tenant.
4508
+ *
4509
+ * **One error for two situations, on purpose.** It is raised identically when
4510
+ * the row does not exist at all and when it exists but belongs to another
4511
+ * tenant, and it carries no field that separates them. That is the whole point:
4512
+ *
4513
+ * - Reporting "forbidden" for a foreign row and "not found" for a missing one
4514
+ * turns any keyed write into a cross-tenant EXISTENCE ORACLE — an attacker
4515
+ * walks ids and learns which ones are real in someone else's tenant, which
4516
+ * is exactly the isolation the `tenant()` mixin exists to provide.
4517
+ * - Collapsing the other way — silently affecting zero rows — is worse than
4518
+ * either: the handler reads it as "the row is gone", not "you may not touch
4519
+ * it", so a genuine isolation breach shows up in an app as a confusing
4520
+ * absent-row branch and never as a security signal.
4521
+ *
4522
+ * So both cases fail LOUDLY and IDENTICALLY. `id` is the key the caller itself
4523
+ * supplied — never another tenant's data.
4524
+ */
4525
+ export declare class TenantRowNotFound extends TenantRowNotFound_base {
4526
+ }
4527
+
4528
+ declare const TenantRowNotFound_base: Schema.TaggedErrorClass<TenantRowNotFound, "TenantRowNotFound", {
4529
+ readonly _tag: Schema.tag<"TenantRowNotFound">;
4530
+ } & {
4531
+ /** The table the keyed write targeted. */
4532
+ table: typeof Schema.String;
4533
+ /** The primary key the CALLER supplied. Echoing it leaks nothing. */
4534
+ id: typeof Schema.String;
4535
+ /** Human-readable explanation for diagnostics + UI. */
4536
+ reason: typeof Schema.String;
4537
+ }>;
4538
+
4367
4539
  /**
4368
4540
  * The subject a `storeForTenant(id)` view runs as — the caller's identity,
4369
4541
  * re-pointed at ONE explicit tenant.
@@ -4383,6 +4555,25 @@ export declare const tenantScopedSubject: (subject: Subject, tenantId: string) =
4383
4555
  readonly type: "serviceAccount";
4384
4556
  }>;
4385
4557
 
4558
+ /**
4559
+ * A write was attempted against a `tenant()`-scoped table, but the
4560
+ * authenticated subject's `tenantId` is null — either anonymous, or
4561
+ * an apiKey / serviceAccount without a tenant binding. Refusing the
4562
+ * write at the boundary is the safe default; a future "system writes"
4563
+ * subject type can opt out.
4564
+ */
4565
+ export declare class TenantScopeViolation extends TenantScopeViolation_base {
4566
+ }
4567
+
4568
+ declare const TenantScopeViolation_base: Schema.TaggedErrorClass<TenantScopeViolation, "TenantScopeViolation", {
4569
+ readonly _tag: Schema.tag<"TenantScopeViolation">;
4570
+ } & {
4571
+ /** The table the violating write targeted. */
4572
+ table: typeof Schema.String;
4573
+ /** Human-readable explanation for diagnostics + UI. */
4574
+ reason: typeof Schema.String;
4575
+ }>;
4576
+
4386
4577
  export declare const toRpc: <Name extends string, Input extends Schema.Schema.Any, Output extends Schema.Schema.Any, Err extends Schema.Schema.All>(descriptor: QueryProcedureDescriptor<Name, Input, Output, Err> | MutationProcedureDescriptor<Name, Input, Output, Err> | ActionProcedureDescriptor<Name, Input, Output, Err> | StreamProcedureDescriptor<Name, Input, Output, Err>) => Rpc.Rpc<Name, Input extends Schema.Struct.Fields ? Schema.Struct<Input> : Input, Stream<Schema.Union<[Schema.Struct<{
4387
4578
  _tag: Schema.Literal<["snapshot"]>;
4388
4579
  revision: typeof Schema.Number;
@@ -4933,8 +5124,8 @@ export declare interface VoltroPlugin {
4933
5124
  * is the WIDENED one. So the server judged against a narrower set than it had
4934
5125
  * advertised, and the framework's own errors failed that judgement:
4935
5126
  *
4936
- * - a guard's `ScopeError` — reported by a consumer, who measured it on every
4937
- * relationship-guarded mutation in their app: a permissions refusal reached
5127
+ * - a guard's `ScopeError` — reported by a deployment, who measured it on every
5128
+ * relationship-guarded mutation in a real app: a permissions refusal reached
4938
5129
  * their client as `InternalError`, so their UI showed "something went wrong"
4939
5130
  * where it should have shown "forbidden";
4940
5131
  * - a cross-table `rule()`'s `BusinessRuleViolation` — unconditional for
package/dist/index.js CHANGED
@@ -138,12 +138,12 @@ var We = d.Union(d.String, d.Number), p = d.Record({
138
138
  decidedAt: d.NullOr(d.String),
139
139
  note: d.NullOr(d.String),
140
140
  relation: d.Literal("to-decide", "requested")
141
- }), N = "channel:", Ze = Symbol.for("@voltro/protocol/reactivityChannels"), Qe = globalThis, P = Qe[Ze] ?? (Qe[Ze] = /* @__PURE__ */ new Map()), $e = /^[a-z][a-z0-9-]*(\.[a-z0-9-]+)*$/, et = (e) => {
142
- if (!$e.test(e)) throw Error(`reactivityChannel('${e}'): invalid channel name.\n Use lowercase kebab segments separated by dots — \`presence\`, \`job-queue\`,
141
+ }), N = "channel:", P = Symbol.for("@voltro/protocol/reactivityChannels"), Ze = globalThis, F = Ze[P] ?? (Ze[P] = /* @__PURE__ */ new Map()), Qe = /^[a-z][a-z0-9-]*(\.[a-z0-9-]+)*$/, $e = (e) => {
142
+ if (!Qe.test(e)) throw Error(`reactivityChannel('${e}'): invalid channel name.\n Use lowercase kebab segments separated by dots — \`presence\`, \`job-queue\`,
143
143
  \`billing.usage\`. A \`:\` is refused because it is the namespace separator in
144
144
  the routing key (\`${N}<name>\`), and an uppercase letter is\n refused because a key that differs only by case reads as one channel and
145
145
  routes as two.`);
146
- let t = P.get(e);
146
+ let t = F.get(e);
147
147
  if (t !== void 0) return t;
148
148
  let n = `${N}${e}`, r = Object.freeze({
149
149
  kind: "reactivity-channel",
@@ -151,15 +151,15 @@ var We = d.Union(d.String, d.Number), p = d.Record({
151
151
  key: n,
152
152
  toString: () => n
153
153
  });
154
- return P.set(e, r), r;
155
- }, tt = (e) => typeof e == "object" && !!e && e.kind === "reactivity-channel", nt = (e) => e.startsWith(N), rt = () => new Set([...P.values()].map((e) => e.key)), F = (e) => tt(e) ? e.key : e, it = (e) => e === void 0 ? [] : Array.isArray(e) ? e.map(F) : [F(e)], at = (e) => e === void 0 ? void 0 : Array.isArray(e) ? e.map(F) : F(e), ot = (e) => {
156
- let t = rt(), n = [];
157
- for (let r of e) for (let e of it(r.source)) !nt(e) || t.has(e) || n.push({
154
+ return F.set(e, r), r;
155
+ }, et = (e) => typeof e == "object" && !!e && e.kind === "reactivity-channel", tt = (e) => e.startsWith(N), nt = () => new Set([...F.values()].map((e) => e.key)), I = (e) => et(e) ? e.key : e, rt = (e) => e === void 0 ? [] : Array.isArray(e) ? e.map(I) : [I(e)], it = (e) => e === void 0 ? void 0 : Array.isArray(e) ? e.map(I) : I(e), at = (e) => {
156
+ let t = nt(), n = [];
157
+ for (let r of e) for (let e of rt(r.source)) !tt(e) || t.has(e) || n.push({
158
158
  procedure: r.name,
159
159
  key: e
160
160
  });
161
161
  return n;
162
- }, st = (e, t) => {
162
+ }, ot = (e, t) => {
163
163
  let n = e?.injectExternalChange;
164
164
  return n !== void 0 && (n.call(e, {
165
165
  table: t.key,
@@ -168,8 +168,8 @@ var We = d.Union(d.String, d.Number), p = d.Record({
168
168
  old: {},
169
169
  origin: "inline"
170
170
  }), !0);
171
- }, ct = (e) => e.internal !== !0, I = (e) => {
172
- if (lt(e), Array.isArray(e.guards) && e.guards.length === 0) throw Error(`${e.name}: \`guards: []\` is empty, so it enforces nothing — but it reads\n at the call site as if this procedure were protected. Omit the field for an
171
+ }, st = (e) => e.internal !== !0, L = (e) => {
172
+ if (ct(e), Array.isArray(e.guards) && e.guards.length === 0) throw Error(`${e.name}: \`guards: []\` is empty, so it enforces nothing — but it reads\n at the call site as if this procedure were protected. Omit the field for an
173
173
  unguarded procedure, or list the scopes required to call it.`);
174
174
  let t = typeof e.source == "string" ? [e.source] : Array.isArray(e.source) ? e.source : void 0;
175
175
  if (t !== void 0 && (t.length === 0 || t.some((e) => String(e).trim() === ""))) throw Error(`${e.name}: \`source\` is empty, so this query declares reactivity and\n subscribes to nothing — it serves one snapshot and never updates again,
@@ -186,7 +186,7 @@ var We = d.Union(d.String, d.Number), p = d.Record({
186
186
  let n = [e.publicApi === void 0 ? void 0 : "publicApi", e.exposeAsTool === void 0 ? void 0 : "exposeAsTool"].filter((e) => e !== void 0);
187
187
  if (n.length === 0) return e;
188
188
  throw Error(`${e.name}: \`internal: true\` cannot be combined with ${n.map((e) => `\`${e}\``).join(" or ")}. \`internal\` takes the procedure OFF the wire; those put it back ON a different one (${n.includes("publicApi") ? "a REST route" : "an agent tool"}), and that surface is projected without consulting the flag — so the procedure would be unreachable from your client and reachable from the internet. Drop \`internal: true\` if the wider surface is intended, or remove the ${n.join(" / ")} annotation if it is not.`);
189
- }, lt = (e) => {
189
+ }, ct = (e) => {
190
190
  let t = e.requiresApproval;
191
191
  if (t !== void 0) {
192
192
  if (!Array.isArray(t.approvers) || t.approvers.length === 0) throw Error(`${e.name}: \`requiresApproval.approvers\` is empty, so NOBODY can approve this\n procedure and every call would park forever. Name the scope(s) an approver must hold
@@ -196,48 +196,48 @@ var We = d.Union(d.String, d.Number), p = d.Record({
196
196
  human from every other, and the second-pair-of-eyes control would enforce nothing.
197
197
  Give the procedure a \`guards:\` decision, or drop \`requiresApproval\`.`);
198
198
  }
199
- }, ut = (e) => e.action !== void 0 && e.resourceType !== void 0, dt = (e) => e.openAccess !== void 0 || e.guards !== void 0 && e.guards.length > 0, L = (e, t, n) => {
199
+ }, lt = (e) => e.action !== void 0 && e.resourceType !== void 0, ut = (e) => e.openAccess !== void 0 || e.guards !== void 0 && e.guards.length > 0, R = (e, t, n) => {
200
200
  if (n === void 0) return t;
201
201
  if (n.trim() === "") throw Error(`${e}: \`openAccess\` needs a REASON, not an empty string. It is the sentence a\n reviewer reads to decide whether this procedure should really be callable
202
202
  without an authorization check — e.g. \`openAccess: 'public pricing, no caller data'\`.`);
203
203
  if (t !== void 0 && t.length > 0) throw Error(`${e}: \`openAccess\` and \`guards\` are two different access decisions, so\n declaring both says the procedure is protected AND open. Keep the guards if a
204
204
  caller must hold a scope; drop them if anyone may call it.`);
205
205
  return [u(n.trim())];
206
- }, R = (e) => I({
206
+ }, z = (e) => L({
207
207
  kind: "query",
208
208
  name: e.name,
209
209
  input: e.input,
210
210
  output: e.output,
211
211
  error: e.error ?? d.Never,
212
- source: at(e.source),
212
+ source: it(e.source),
213
213
  cache: e.cache,
214
- guards: L(e.name, e.guards, e.openAccess),
214
+ guards: R(e.name, e.guards, e.openAccess),
215
215
  openAccess: e.openAccess,
216
216
  publicApi: e.publicApi,
217
217
  exposeAsTool: e.exposeAsTool,
218
218
  internal: e.internal,
219
219
  overridesPlugin: e.overridesPlugin
220
- }), z = (e) => I({
220
+ }), B = (e) => L({
221
221
  kind: "mutation",
222
222
  name: e.name,
223
223
  input: e.input,
224
224
  output: e.output,
225
225
  error: e.error ?? d.Never,
226
226
  target: e.target,
227
- guards: L(e.name, e.guards, e.openAccess),
227
+ guards: R(e.name, e.guards, e.openAccess),
228
228
  openAccess: e.openAccess,
229
229
  publicApi: e.publicApi,
230
230
  exposeAsTool: e.exposeAsTool,
231
231
  requiresApproval: e.requiresApproval,
232
232
  internal: e.internal,
233
233
  overridesPlugin: e.overridesPlugin
234
- }), B = (e) => I({
234
+ }), V = (e) => L({
235
235
  kind: "action",
236
236
  name: e.name,
237
237
  input: e.input,
238
238
  output: e.output,
239
239
  error: e.error ?? d.Never,
240
- guards: L(e.name, e.guards, e.openAccess),
240
+ guards: R(e.name, e.guards, e.openAccess),
241
241
  openAccess: e.openAccess,
242
242
  source: e.source,
243
243
  target: e.target,
@@ -246,7 +246,7 @@ var We = d.Union(d.String, d.Number), p = d.Record({
246
246
  requiresApproval: e.requiresApproval,
247
247
  internal: e.internal,
248
248
  overridesPlugin: e.overridesPlugin
249
- }), ft = (e) => I({
249
+ }), dt = (e) => L({
250
250
  kind: "stream",
251
251
  name: e.name,
252
252
  input: e.input,
@@ -254,42 +254,42 @@ var We = d.Union(d.String, d.Number), p = d.Record({
254
254
  error: e.error ?? d.Never,
255
255
  internal: e.internal,
256
256
  overridesPlugin: e.overridesPlugin,
257
- guards: L(e.name, e.guards, e.openAccess),
257
+ guards: R(e.name, e.guards, e.openAccess),
258
258
  openAccess: e.openAccess
259
- }), V = (e, t) => t && t.length > 0 ? d.Union(e, ...t) : e, H = (e) => e !== void 0 && e.some((e) => !l(e)), pt = (e, t) => H(t) ? d.Union(e, c, s) : e, mt = (e) => d.Union(e, x), ht = (e, t) => t === void 0 ? e : d.Union(e, A), U = (e, t) => {
259
+ }), H = (e, t) => t && t.length > 0 ? d.Union(e, ...t) : e, U = (e) => e !== void 0 && e.some((e) => !l(e)), ft = (e, t) => U(t) ? d.Union(e, c, s) : e, pt = (e) => d.Union(e, x), mt = (e, t) => t === void 0 ? e : d.Union(e, A), W = (e, t) => {
260
260
  if (t === "stream") return e.error;
261
- let n = pt(e.error, e.guards);
262
- return t === "query" ? n : ht(t === "mutation" ? mt(n) : n, e.requiresApproval);
263
- }, gt = (e, t) => f.make(e.name, {
264
- payload: b(e.input, e.name, H(e.guards)),
261
+ let n = ft(e.error, e.guards);
262
+ return t === "query" ? n : mt(t === "mutation" ? pt(n) : n, e.requiresApproval);
263
+ }, ht = (e, t) => f.make(e.name, {
264
+ payload: b(e.input, e.name, U(e.guards)),
265
265
  success: v(e.output),
266
- error: V(U(e, "query"), t),
266
+ error: H(W(e, "query"), t),
267
267
  stream: !0
268
+ }), gt = (e, t) => f.make(e.name, {
269
+ payload: b(e.input, e.name, U(e.guards)),
270
+ success: e.output,
271
+ error: H(W(e, "mutation"), t)
268
272
  }), _t = (e, t) => f.make(e.name, {
269
- payload: b(e.input, e.name, H(e.guards)),
273
+ payload: b(e.input, e.name, U(e.guards)),
270
274
  success: e.output,
271
- error: V(U(e, "mutation"), t)
275
+ error: H(W(e, "action"), t)
272
276
  }), vt = (e, t) => f.make(e.name, {
273
- payload: b(e.input, e.name, H(e.guards)),
274
- success: e.output,
275
- error: V(U(e, "action"), t)
276
- }), yt = (e, t) => f.make(e.name, {
277
- payload: b(e.input, e.name, H(e.guards)),
277
+ payload: b(e.input, e.name, U(e.guards)),
278
278
  success: e.element,
279
- error: V(e.error, t),
279
+ error: H(e.error, t),
280
280
  stream: !0
281
- }), bt = (e) => {
281
+ }), yt = (e) => {
282
282
  if (typeof e != "object" || !e) return;
283
283
  let t = e._tag;
284
284
  return typeof t == "string" ? t : void 0;
285
- }, xt = (e) => {
285
+ }, bt = (e) => {
286
286
  switch (e.kind) {
287
- case "query": return gt(e);
288
- case "mutation": return _t(e);
289
- case "action": return vt(e);
290
- case "stream": return yt(e);
287
+ case "query": return ht(e);
288
+ case "mutation": return gt(e);
289
+ case "action": return _t(e);
290
+ case "stream": return vt(e);
291
291
  }
292
- }, St = (e) => {
292
+ }, xt = (e) => {
293
293
  let t = e.input, n = t === void 0 ? {} : { input: t }, r = e.output, i = r === void 0 ? {} : { output: r };
294
294
  if (e.kind === "query") return {
295
295
  kind: "query",
@@ -330,7 +330,7 @@ var We = d.Union(d.String, d.Number), p = d.Record({
330
330
  ..."shapeItem" in e && e.shapeItem !== void 0 ? { shapeItem: e.shapeItem } : {}
331
331
  }))
332
332
  };
333
- }, Ct = 7500, wt = (e) => typeof e == "object" && !!e && e.kind === "event", Tt = (e) => {
333
+ }, St = 7500, Ct = (e) => typeof e == "object" && !!e && e.kind === "event", wt = (e) => {
334
334
  if (e.name.length === 0) throw Error("defineEvent: `name` must not be empty");
335
335
  if (/\s/.test(e.name)) throw Error(`defineEvent("${e.name}"): \`name\` must not contain whitespace.\n The name is used as a broker subject segment. NATS refuses a subject with
336
336
  whitespace and delivers nothing — silently, and only on that broker, so an
@@ -365,69 +365,69 @@ var We = d.Union(d.String, d.Number), p = d.Record({
365
365
  webhook: e.webhook,
366
366
  delivery: e.delivery
367
367
  };
368
- }, Et = (e) => d.Struct({
368
+ }, Tt = (e) => d.Struct({
369
369
  _tag: d.Literal("event"),
370
370
  origin: d.String,
371
371
  n: d.Number,
372
372
  emittedAt: d.Number,
373
373
  payload: e
374
- }), Dt = d.Struct({
374
+ }), Et = d.Struct({
375
375
  _tag: d.Literal("gap"),
376
376
  missed: d.Number,
377
377
  reason: d.Literal("buffer", "resume")
378
- }), Ot = d.Struct({ _tag: d.Literal("attached") }), kt = (e) => d.Union(Ot, Et(e), Dt), At = d.Struct({
378
+ }), Dt = d.Struct({ _tag: d.Literal("attached") }), Ot = (e) => d.Union(Dt, Tt(e), Et), kt = d.Struct({
379
379
  origin: d.String,
380
380
  n: d.Number
381
- }), jt = (e) => d.Struct({
381
+ }), At = (e) => d.Struct({
382
382
  key: e,
383
- resume: d.optional(d.Array(At))
384
- }), Mt = (e, t) => {
383
+ resume: d.optional(d.Array(kt))
384
+ }), jt = (e, t) => {
385
385
  let n = e.guards !== void 0 && e.guards.some((e) => !l(e)) ? d.Union(c, s) : d.Never, r = t && t.length > 0 ? d.Union(n, ...t) : n;
386
386
  return f.make(e.name, {
387
- payload: b(jt(e.key), e.name, H(e.guards)),
388
- success: kt(e.payload),
387
+ payload: b(At(e.key), e.name, U(e.guards)),
388
+ success: Ot(e.payload),
389
389
  error: r,
390
390
  stream: !0
391
391
  });
392
- }, Nt = class extends d.TaggedError()("EventPayloadInvalid", {
392
+ }, Mt = class extends d.TaggedError()("EventPayloadInvalid", {
393
393
  event: d.String,
394
394
  message: d.String
395
- }) {}, Pt = class extends d.TaggedError()("EventKeyInvalid", {
395
+ }) {}, Nt = class extends d.TaggedError()("EventKeyInvalid", {
396
396
  event: d.String,
397
397
  message: d.String
398
- }) {}, Ft = class extends d.TaggedError()("EventPayloadTooLarge", {
398
+ }) {}, Pt = class extends d.TaggedError()("EventPayloadTooLarge", {
399
399
  event: d.String,
400
400
  bytes: d.Number,
401
401
  limit: d.Number
402
- }) {}, It = (e) => {
402
+ }) {}, Ft = (e) => {
403
403
  if (typeof e != "object" || !e) return JSON.stringify(e) ?? "null";
404
404
  let t = Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t));
405
405
  return JSON.stringify(t);
406
- }, Lt = "\0", Rt = (e, t, n) => [
406
+ }, It = "\0", Lt = (e, t, n) => [
407
407
  e ?? "~",
408
408
  t,
409
- It(n)
410
- ].join("\0"), zt = (e) => {
409
+ Ft(n)
410
+ ].join("\0"), Rt = (e) => {
411
411
  let [t = "~", n = "", r = ""] = e.split("\0");
412
412
  return {
413
413
  tenantId: t === "~" ? null : t,
414
414
  event: n,
415
415
  key: r
416
416
  };
417
- }, Bt = (e) => e.split("\0").join(" · "), Vt = (e) => e, Ht = (e) => e, Ut = (e) => {
417
+ }, zt = (e) => e.split("\0").join(" · "), Bt = (e) => e, Vt = (e) => e, Ht = (e) => {
418
418
  let t = e.alias?.trim(), n = e.instance?.trim(), r = t !== void 0 && t !== "" ? t : e.base;
419
419
  return n !== void 0 && n !== "" ? `${r}#${n}` : r;
420
- }, Wt = (e) => {
420
+ }, Ut = (e) => {
421
421
  if (e.length !== 0) return (t, n) => e.reduceRight((e, t) => t(e, n), t);
422
- }, Gt = (e, t) => {
422
+ }, Wt = (e, t) => {
423
423
  let n = He.GenericTag(e);
424
424
  return {
425
425
  Tag: n,
426
426
  Live: Ue.succeed(n, t)
427
427
  };
428
- }, Kt = (e, t, n) => {
428
+ }, Gt = (e, t, n) => {
429
429
  if (!t) return { ok: !0 };
430
- let r = W(n);
430
+ let r = G(n);
431
431
  if (!r) return {
432
432
  ok: !1,
433
433
  reason: `cannot parse runningVersion "${n}"`
@@ -435,12 +435,12 @@ var We = d.Union(d.String, d.Number), p = d.Record({
435
435
  let i = t.trim();
436
436
  if (i === "*" || i === "") return { ok: !0 };
437
437
  let a = i.split(/\s+/).filter((e) => e.length > 0);
438
- for (let i of a) if (!qt(i, r)) return {
438
+ for (let i of a) if (!Kt(i, r)) return {
439
439
  ok: !1,
440
440
  reason: `plugin "${e}" requires framework ${t}, running ${n}`
441
441
  };
442
442
  return { ok: !0 };
443
- }, W = (e) => {
443
+ }, G = (e) => {
444
444
  let t = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9a-zA-Z.-]+))?$/.exec(e.trim());
445
445
  return t ? {
446
446
  major: Number(t[1]),
@@ -448,44 +448,44 @@ var We = d.Union(d.String, d.Number), p = d.Record({
448
448
  patch: Number(t[3]),
449
449
  pre: t[4] ?? ""
450
450
  } : null;
451
- }, G = (e, t) => e.major === t.major ? e.minor === t.minor ? e.patch === t.patch ? e.pre && !t.pre ? -1 : !e.pre && t.pre ? 1 : e.pre && t.pre ? e.pre < t.pre ? -1 : +(e.pre > t.pre) : 0 : e.patch - t.patch : e.minor - t.minor : e.major - t.major, qt = (e, t) => {
451
+ }, K = (e, t) => e.major === t.major ? e.minor === t.minor ? e.patch === t.patch ? e.pre && !t.pre ? -1 : !e.pre && t.pre ? 1 : e.pre && t.pre ? e.pre < t.pre ? -1 : +(e.pre > t.pre) : 0 : e.patch - t.patch : e.minor - t.minor : e.major - t.major, Kt = (e, t) => {
452
452
  if (e === "*") return !0;
453
453
  if (e.startsWith("^")) {
454
- let n = W(e.slice(1));
455
- return !n || t.major !== n.major ? !1 : G(t, n) >= 0;
454
+ let n = G(e.slice(1));
455
+ return !n || t.major !== n.major ? !1 : K(t, n) >= 0;
456
456
  }
457
457
  if (e.startsWith("~")) {
458
- let n = W(e.slice(1));
459
- return !n || t.major !== n.major || t.minor !== n.minor ? !1 : G(t, n) >= 0;
458
+ let n = G(e.slice(1));
459
+ return !n || t.major !== n.major || t.minor !== n.minor ? !1 : K(t, n) >= 0;
460
460
  }
461
461
  let n = /^(>=|<=|>|<)(.+)$/.exec(e);
462
462
  if (n) {
463
- let e = n[1], r = W(n[2]);
463
+ let e = n[1], r = G(n[2]);
464
464
  if (!r) return !1;
465
- let i = G(t, r);
465
+ let i = K(t, r);
466
466
  if (e === ">=") return i >= 0;
467
467
  if (e === "<=") return i <= 0;
468
468
  if (e === ">") return i > 0;
469
469
  if (e === "<") return i < 0;
470
470
  }
471
- let r = W(e);
472
- return r ? G(t, r) === 0 : !1;
473
- }, K = d.Literal("running", "succeeded", "failed", "cancelled", "suspended"), Jt = d.Literal("cancel", "terminate", "abandon"), Yt = d.Struct({
471
+ let r = G(e);
472
+ return r ? K(t, r) === 0 : !1;
473
+ }, q = d.Literal("running", "succeeded", "failed", "cancelled", "suspended"), qt = d.Literal("cancel", "terminate", "abandon"), Jt = d.Struct({
474
474
  mode: d.String,
475
475
  dueAt: d.NullOr(d.Number),
476
476
  retryAfterMs: d.NullOr(d.Number),
477
477
  intentId: d.NullOr(d.String)
478
- }), Xt = d.Struct({
478
+ }), Yt = d.Struct({
479
479
  id: d.String,
480
480
  workflowName: d.String,
481
481
  executionId: d.NullOr(d.String),
482
482
  status: d.Literal("running", "queued", "dropped", "skipped"),
483
- deferral: d.optional(Yt)
484
- }), q = d.Struct({
483
+ deferral: d.optional(Jt)
484
+ }), J = d.Struct({
485
485
  id: d.String,
486
486
  tag: d.String,
487
487
  executionId: d.String,
488
- status: K,
488
+ status: q,
489
489
  payload: d.Unknown,
490
490
  workflowVersion: d.NullOr(d.String),
491
491
  workflowPatches: d.NullOr(d.Unknown),
@@ -500,12 +500,12 @@ var We = d.Union(d.String, d.Number), p = d.Record({
500
500
  durationMs: d.NullOr(d.Number),
501
501
  traceId: d.NullOr(d.String),
502
502
  parentExecutionId: d.NullOr(d.String),
503
- parentClosePolicy: d.NullOr(Jt)
504
- }), Zt = d.Struct({
503
+ parentClosePolicy: d.NullOr(qt)
504
+ }), Xt = d.Struct({
505
505
  tag: d.optional(d.String),
506
- status: d.optional(K),
506
+ status: d.optional(q),
507
507
  limit: d.optional(d.Number)
508
- }), Qt = d.Struct({
508
+ }), Zt = d.Struct({
509
509
  id: d.String,
510
510
  runId: d.String,
511
511
  stepName: d.String,
@@ -520,7 +520,7 @@ var We = d.Union(d.String, d.Number), p = d.Record({
520
520
  startedAt: d.Date,
521
521
  completedAt: d.NullOr(d.Date),
522
522
  durationMs: d.NullOr(d.Number)
523
- }), $t = d.Struct({
523
+ }), Qt = d.Struct({
524
524
  id: d.String,
525
525
  runId: d.String,
526
526
  eventType: d.String,
@@ -528,7 +528,7 @@ var We = d.Union(d.String, d.Number), p = d.Record({
528
528
  occurredAt: d.Date,
529
529
  stepName: d.NullOr(d.String),
530
530
  attempt: d.NullOr(d.Number)
531
- }), en = d.Struct({
531
+ }), $t = d.Struct({
532
532
  id: d.String,
533
533
  name: d.String,
534
534
  payload: d.Unknown,
@@ -536,7 +536,7 @@ var We = d.Union(d.String, d.Number), p = d.Record({
536
536
  subject: d.NullOr(d.Unknown),
537
537
  traceId: d.NullOr(d.String),
538
538
  occurredAt: d.Date
539
- }), tn = d.Struct({
539
+ }), en = d.Struct({
540
540
  id: d.String,
541
541
  eventId: d.String,
542
542
  eventName: d.String,
@@ -549,108 +549,146 @@ var We = d.Union(d.String, d.Number), p = d.Record({
549
549
  errorMessage: d.NullOr(d.String),
550
550
  createdAt: d.Date,
551
551
  completedAt: d.NullOr(d.Date)
552
- }), nn = d.Struct({ id: d.String }), J = d.Struct({ runId: d.String }), rn = d.Struct({
552
+ }), tn = d.Struct({ id: d.String }), Y = d.Struct({ runId: d.String }), nn = d.Struct({
553
553
  name: d.optional(d.String),
554
554
  limit: d.optional(d.Number)
555
- }), an = d.Struct({ eventId: d.String }), Y = d.Struct({
555
+ }), rn = d.Struct({ eventId: d.String }), X = d.Struct({
556
556
  workflowName: d.String,
557
557
  executionId: d.String
558
- }), on = d.Struct({
558
+ }), an = d.Struct({
559
559
  id: d.String,
560
560
  signalName: d.String,
561
561
  payload: d.optional(d.Unknown)
562
- }), sn = d.Struct({
562
+ }), on = d.Struct({
563
563
  id: d.String,
564
564
  updateName: d.String,
565
565
  payload: d.optional(d.Unknown),
566
566
  timeoutMs: d.optional(d.Number)
567
- }), cn = d.Struct({
567
+ }), sn = d.Struct({
568
568
  eventId: d.String,
569
569
  updateId: d.String,
570
570
  completedEventId: d.String,
571
571
  result: d.Unknown
572
- }), ln = R({
572
+ }), cn = z({
573
573
  name: "__voltro.workflow.run",
574
574
  source: "_voltro_workflow_runs",
575
- input: nn,
576
- output: d.Array(q)
577
- }), un = R({
575
+ input: tn,
576
+ output: d.Array(J)
577
+ }), ln = z({
578
578
  name: "__voltro.workflow.runs",
579
579
  source: "_voltro_workflow_runs",
580
- input: Zt,
581
- output: d.Array(q)
582
- }), dn = R({
580
+ input: Xt,
581
+ output: d.Array(J)
582
+ }), un = z({
583
583
  name: "__voltro.workflow.run.steps",
584
584
  source: "_voltro_workflow_run_steps",
585
- input: J,
586
- output: d.Array(Qt)
587
- }), fn = R({
585
+ input: Y,
586
+ output: d.Array(Zt)
587
+ }), dn = z({
588
588
  name: "__voltro.workflow.run.events",
589
589
  source: "_voltro_workflow_run_events",
590
- input: J,
591
- output: d.Array($t)
592
- }), pn = R({
590
+ input: Y,
591
+ output: d.Array(Qt)
592
+ }), fn = z({
593
593
  name: "__voltro.workflow.domainEvents",
594
594
  source: "_voltro_workflow_events",
595
- input: rn,
596
- output: d.Array(en)
597
- }), mn = R({
595
+ input: nn,
596
+ output: d.Array($t)
597
+ }), pn = z({
598
598
  name: "__voltro.workflow.event.deliveries",
599
599
  source: "_voltro_workflow_event_deliveries",
600
- input: an,
601
- output: d.Array(tn)
602
- }), hn = B({
600
+ input: rn,
601
+ output: d.Array(en)
602
+ }), mn = V({
603
603
  name: "__voltro.workflow.cancel",
604
- input: Y,
604
+ input: X,
605
605
  output: d.Struct({ ok: d.Boolean })
606
- }), gn = B({
606
+ }), hn = V({
607
607
  name: "__voltro.workflow.resume",
608
- input: Y,
608
+ input: X,
609
609
  output: d.Struct({ ok: d.Boolean })
610
- }), _n = B({
610
+ }), gn = V({
611
611
  name: "__voltro.workflow.signal",
612
- input: on,
612
+ input: an,
613
613
  output: d.Struct({ eventId: d.String })
614
- }), vn = B({
614
+ }), _n = V({
615
615
  name: "__voltro.workflow.update",
616
- input: sn,
617
- output: cn
618
- }), yn = "__voltro.undo.log", bn = "__voltro.undo.apply", xn = "__voltro.undo.redo", Sn = d.Struct({
616
+ input: on,
617
+ output: sn
618
+ }), vn = "__voltro.undo.log", yn = "__voltro.undo.apply", bn = "__voltro.undo.redo", xn = d.Struct({
619
619
  id: d.String,
620
620
  tag: d.String,
621
621
  label: d.NullOr(d.String),
622
622
  undone: d.Boolean,
623
623
  crossesAction: d.Boolean,
624
624
  createdAt: d.String
625
- }), Cn = class extends d.TaggedError()("UndoNotFound", { invocationId: d.String }) {}, wn = class extends d.TaggedError()("UndoForbidden", { invocationId: d.String }) {}, X = class extends d.TaggedError()("UndoConflict", {
625
+ }), Sn = class extends d.TaggedError()("UndoNotFound", { invocationId: d.String }) {}, Cn = class extends d.TaggedError()("UndoForbidden", { invocationId: d.String }) {}, wn = class extends d.TaggedError()("UndoConflict", {
626
626
  invocationId: d.String,
627
627
  reason: d.Literal("conflict", "action")
628
- }) {}, Tn = d.Union(Cn, wn, X), En = R({
629
- name: yn,
628
+ }) {}, Tn = d.Union(Sn, Cn, wn), En = z({
629
+ name: vn,
630
630
  source: "_voltro_undo_log",
631
631
  input: d.Struct({ limit: d.optional(d.Number) }),
632
- output: d.Array(Sn),
632
+ output: d.Array(xn),
633
633
  openAccess: "subject-scoped by construction: lists only the calling subject's own undoable actions"
634
- }), Dn = z({
635
- name: bn,
634
+ }), Dn = B({
635
+ name: yn,
636
636
  input: d.Struct({ invocationId: d.String }),
637
637
  output: d.Struct({ ok: d.Boolean }),
638
638
  error: Tn,
639
639
  openAccess: "subject-scoped by construction: undo is per-actor — another subject's invocation fails typed with UndoForbidden"
640
- }), On = z({
641
- name: xn,
640
+ }), On = B({
641
+ name: bn,
642
642
  input: d.Struct({ invocationId: d.String }),
643
643
  output: d.Struct({ ok: d.Boolean }),
644
644
  error: Tn,
645
645
  openAccess: "subject-scoped by construction: redo is per-actor — another subject's invocation fails typed with UndoForbidden"
646
- }), kn = "__voltro.approvals.pending", An = "__voltro.approvals.decide", jn = R({
647
- name: kn,
646
+ }), kn = class extends d.TaggedError()("TenantScopeViolation", {
647
+ table: d.String,
648
+ reason: d.String
649
+ }) {}, An = class extends d.TaggedError()("StoreOperationFailed", {
650
+ operation: d.String,
651
+ table: d.String,
652
+ cause: d.String
653
+ }) {}, jn = class extends d.TaggedError()("TableValidationFailed", {
654
+ table: d.String,
655
+ summary: d.String,
656
+ issues: d.Array(d.Struct({
657
+ path: d.String,
658
+ message: d.String
659
+ }))
660
+ }) {}, Mn = class extends d.TaggedError()("TenantRowNotFound", {
661
+ table: d.String,
662
+ id: d.String,
663
+ reason: d.String
664
+ }) {}, Nn = class extends d.TaggedError()("ServerOnlyColumnWrite", {
665
+ table: d.String,
666
+ columns: d.Array(d.String)
667
+ }) {}, Pn = class extends d.TaggedError()("ConstraintViolation", {
668
+ kind: d.Literal("foreignKey", "foreignKeyInUse", "unique", "notNull", "check"),
669
+ table: d.String,
670
+ operation: d.String,
671
+ constraint: d.optional(d.String),
672
+ column: d.optional(d.String)
673
+ }) {
674
+ get message() {
675
+ let e = this.constraint ?? this.column, t = e === void 0 ? `on ${this.table}` : `${e} on ${this.table}`;
676
+ switch (this.kind) {
677
+ case "foreignKey": return `foreign key ${t}: the referenced row does not exist`;
678
+ case "foreignKeyInUse": return `foreign key ${t}: the row is still referenced by other rows`;
679
+ case "unique": return `unique constraint ${t}: a row with this value already exists`;
680
+ case "notNull": return `not-null constraint ${t}: the column requires a value`;
681
+ case "check": return `check constraint ${t}: the row does not satisfy it`;
682
+ }
683
+ }
684
+ }, Fn = "__voltro.approvals.pending", Z = "__voltro.approvals.decide", In = z({
685
+ name: Fn,
648
686
  source: "_voltro_approvals",
649
687
  input: d.Struct({ limit: d.optional(d.Number) }),
650
688
  output: d.Array(M),
651
689
  openAccess: "the answer is scoped to the caller — a row appears only if they requested it or hold its recorded approver scopes, so an anonymous caller sees nothing"
652
- }), Mn = z({
653
- name: An,
690
+ }), Ln = B({
691
+ name: Z,
654
692
  input: d.Struct({
655
693
  approvalId: d.String,
656
694
  decision: d.Literal("approve", "reject"),
@@ -662,33 +700,33 @@ var We = d.Union(d.String, d.Number), p = d.Record({
662
700
  }),
663
701
  error: j,
664
702
  openAccess: "the approver authority is the PENDING ROW's own recorded scopes (plus an unconditional self-approval refusal), checked in-handler — a descriptor-level scope would have to be the union of every approval-requiring procedure in the app"
665
- }), Nn = "__voltro.connections.list", Pn = "__voltro.connections.start", Fn = "__voltro.connections.submitToken", In = "__voltro.connections.disconnect", Z = d.Literal("oauth2", "pat"), Ln = d.Literal("disconnected", "connected", "expired", "revoked", "error"), Rn = d.Struct({
703
+ }), Rn = "__voltro.connections.list", zn = "__voltro.connections.start", Bn = "__voltro.connections.submitToken", Vn = "__voltro.connections.disconnect", Q = d.Literal("oauth2", "pat"), Hn = d.Literal("disconnected", "connected", "expired", "revoked", "error"), Un = d.Struct({
666
704
  connectionId: d.String,
667
- kind: Z,
705
+ kind: Q,
668
706
  label: d.String,
669
- status: Ln,
707
+ status: Hn,
670
708
  accountId: d.NullOr(d.String),
671
709
  accountLabel: d.NullOr(d.String),
672
710
  scopes: d.Array(d.String),
673
711
  expiresAt: d.NullOr(d.String),
674
712
  lastError: d.NullOr(d.String),
675
713
  connectedAt: d.NullOr(d.String)
676
- }), zn = class extends d.TaggedError()("ConnectionNotDeclared", { connectionId: d.String }) {}, Bn = class extends d.TaggedError()("ConnectionSubjectRequired", { connectionId: d.String }) {}, Vn = class extends d.TaggedError()("ConnectionKindMismatch", {
714
+ }), Wn = class extends d.TaggedError()("ConnectionNotDeclared", { connectionId: d.String }) {}, Gn = class extends d.TaggedError()("ConnectionSubjectRequired", { connectionId: d.String }) {}, Kn = class extends d.TaggedError()("ConnectionKindMismatch", {
677
715
  connectionId: d.String,
678
- expected: Z,
679
- actual: Z
680
- }) {}, Q = class extends d.TaggedError()("ConnectionHandshakeFailed", {
716
+ expected: Q,
717
+ actual: Q
718
+ }) {}, qn = class extends d.TaggedError()("ConnectionHandshakeFailed", {
681
719
  connectionId: d.String,
682
720
  reason: d.String,
683
721
  transient: d.Boolean
684
- }) {}, $ = d.Union(zn, Bn, Vn, Q), Hn = R({
685
- name: Nn,
722
+ }) {}, $ = d.Union(Wn, Gn, Kn, qn), Jn = z({
723
+ name: Rn,
686
724
  source: "_voltro_connections",
687
725
  input: d.Struct({}),
688
- output: d.Array(Rn),
726
+ output: d.Array(Un),
689
727
  openAccess: "self-scoped read: projects the declared connections for the calling subject only (its own connect/disconnect state)"
690
- }), Un = B({
691
- name: Pn,
728
+ }), Yn = V({
729
+ name: zn,
692
730
  input: d.Struct({
693
731
  connectionId: d.String,
694
732
  redirectTo: d.optional(d.String)
@@ -699,8 +737,8 @@ var We = d.Union(d.String, d.Number), p = d.Record({
699
737
  }),
700
738
  error: $,
701
739
  openAccess: "self-service: begins an oauth handshake that stores a credential for the calling subject only; anonymous callers fail typed with ConnectionSubjectRequired"
702
- }), Wn = z({
703
- name: Fn,
740
+ }), Xn = B({
741
+ name: Bn,
704
742
  input: d.Struct({
705
743
  connectionId: d.String,
706
744
  token: d.String
@@ -708,15 +746,15 @@ var We = d.Union(d.String, d.Number), p = d.Record({
708
746
  output: d.Struct({ ok: d.Boolean }),
709
747
  error: $,
710
748
  openAccess: "self-service: stores a pasted token as the calling subject's own credential; anonymous callers fail typed with ConnectionSubjectRequired"
711
- }), Gn = z({
712
- name: In,
749
+ }), Zn = B({
750
+ name: Vn,
713
751
  input: d.Struct({ connectionId: d.String }),
714
752
  output: d.Struct({ ok: d.Boolean }),
715
753
  error: $,
716
754
  openAccess: "self-service: deletes only the calling subject's own credential row for this connection"
717
- }), Kn = (e) => {
755
+ }), Qn = (e) => {
718
756
  let t = e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : 0;
719
757
  return Number.isNaN(t) ? 0 : t;
720
- }, qn = 1;
758
+ }, $n = 1;
721
759
  //#endregion
722
- export { Oe as ADMIN_SCOPE, Ce as APIKEY_ISSUE_ORG_SCOPE, Ee as APIKEY_ISSUE_OTHER_SCOPE, ve as APIKEY_ISSUE_SELF_SCOPE, An as APPROVALS_DECIDE_TAG, kn as APPROVALS_PENDING_TAG, j as ApprovalDecisionErrors, A as ApprovalErrors, E as ApprovalExpired, O as ApprovalForbidden, C as ApprovalNotFound, D as ApprovalNotPending, T as ApprovalRejected, S as ApprovalRequired, w as ApprovalSelfApproval, k as ApprovalUnavailable, Ae as AuthMiddleware, x as BusinessRuleViolation, Nn as CONNECTIONS_LIST_TAG, In as CONNECTION_DISCONNECT_TAG, Pn as CONNECTION_START_TAG, Fn as CONNECTION_SUBMIT_TOKEN_TAG, Q as ConnectionHandshakeFailed, ce as ConnectionInfo, i as ConnectionInfoMiddleware, Z as ConnectionKind, Vn as ConnectionKindMismatch, zn as ConnectionNotDeclared, Rn as ConnectionState, Ln as ConnectionStatus, Bn as ConnectionSubjectRequired, r as DEFAULT_SCOPE_CACHE_MAX_ENTRIES, ie as DEFAULT_SCOPE_CACHE_TTL_MS, Lt as EVENT_ROUTE_SEP, Pt as EventKeyInvalid, Nt as EventPayloadInvalid, Ft as EventPayloadTooLarge, be as IMPERSONATION_METADATA_KEY, Ct as MAX_EVENT_ENVELOPE_BYTES, qn as PROTOCOL_VERSION, M as PendingApproval, N as REACTIVITY_CHANNEL_PREFIX, c as ScopeError, e as Subject, ye as SubjectIdentity, re as SubjectService, bn as UNDO_APPLY_TAG, yn as UNDO_LOG_TAG, xn as UNDO_REDO_TAG, s as Unauthenticated, X as UndoConflict, wn as UndoForbidden, Sn as UndoLogEntry, Cn as UndoNotFound, Y as WorkflowControlInputSchema, en as WorkflowDomainEventRowSchema, rn as WorkflowDomainEventsInputSchema, an as WorkflowEventDeliveriesInputSchema, tn as WorkflowEventDeliveryRowSchema, Jt as WorkflowParentClosePolicySchema, $t as WorkflowRunEventRowSchema, Xt as WorkflowRunHandleSchema, nn as WorkflowRunRefSchema, q as WorkflowRunRowSchema, K as WorkflowRunStatusSchema, Qt as WorkflowRunStepRowSchema, J as WorkflowRunTableRefSchema, Zt as WorkflowRunsInputSchema, on as WorkflowSignalInputSchema, Yt as WorkflowStartDeferralSchema, sn as WorkflowUpdateInputSchema, cn as WorkflowUpdateResultSchema, vt as actionToRpc, we as advisoryResourceGuardWarning, ae as anonymousSubject, Ye as applyRowPatch, a as applyScopeDecision, Mn as approvalsDecideDescriptor, jn as approvalsPendingQueryDescriptor, te as assertAuthenticated, ze as beginIdempotent, Kt as checkFrameworkCompat, De as checkGuards, me as checkGuardsEffect, ne as composeAuthStrategies, Wt as composeRpcInterceptors, Gn as connectionDisconnectDescriptor, Un as connectionStartDescriptor, Wn as connectionSubmitTokenDescriptor, Hn as connectionsListQueryDescriptor, rt as declaredReactivityChannelKeys, B as defineAction, Tt as defineEvent, z as defineMutation, Vt as definePlugin, Ht as definePluginRoute, Gt as definePluginService, R as defineQuery, ft as defineStream, qe as diffRows, xe as effectiveScopes, It as encodeEventKey, bt as errorTag, Ot as eventAttached, Et as eventEnvelope, Dt as eventGap, At as eventResumePoint, Rt as eventRoute, kt as eventStreamEvent, jt as eventSubscribeInput, Mt as eventToRpc, Ie as failIdempotent, ke as findAdvisoryResourceGuards, Pe as finishIdempotent, Bt as formatEventRoute, he as getPolicyGuardResolver, ge as getResourceScopeResolver, dt as hasAccessDecision, oe as hasCallbackRoutes, Te as hasEffectiveScope, H as hasEnforcedGuard, Se as hasScope, g as idToPath, Re as idempotencyScope, y as inputLabel, wt as isEventDescriptor, Je as isIdKeyed, l as isOpenAccess, _e as isPolicyCheck, ut as isPolicyGuard, tt as isReactivityChannel, nt as isReactivityChannelKey, Ne as isSystemSubject, ct as isWireReachable, t as makeScopeCache, Be as memoryIdempotencyStore, fe as missingAccessDecision, _t as mutationToRpc, St as normalizeDescriptor, at as normalizeSource, u as openAccessSpec, zt as parseEventRoute, Ge as pathToId, Ut as pluginInstanceName, st as publishReactivity, Ve as publishServerError, gt as queryToRpc, ue as rawImpersonationMark, et as reactivityChannel, Me as requireScope, m as rowPatchOpSchema, h as rowPatchSchema, ee as scopeCacheKey, pe as setEffectiveScopes, je as setPolicyGuardResolver, se as setResourceScopeResolver, it as sourceKeys, yt as streamToRpc, b as strictInput, le as subjectIdentity, n as subjectScopes, Le as subscribeServerErrors, v as subscriptionEvent, de as systemSubject, o as tenantScopedSubject, xt as toRpc, Kn as tsMs, ot as undeclaredChannelKeys, Dn as undoApplyDescriptor, En as undoLogQueryDescriptor, On as undoRedoDescriptor, U as wireErrorUnion, hn as workflowCancelDescriptor, pn as workflowDomainEventsQueryDescriptor, mn as workflowEventDeliveriesQueryDescriptor, gn as workflowResumeDescriptor, fn as workflowRunEventsQueryDescriptor, ln as workflowRunQueryDescriptor, dn as workflowRunStepsQueryDescriptor, un as workflowRunsQueryDescriptor, _n as workflowSignalDescriptor, vn as workflowUpdateDescriptor, Fe as wsMutationIdempotencyScope };
760
+ export { Oe as ADMIN_SCOPE, Ce as APIKEY_ISSUE_ORG_SCOPE, Ee as APIKEY_ISSUE_OTHER_SCOPE, ve as APIKEY_ISSUE_SELF_SCOPE, Z as APPROVALS_DECIDE_TAG, Fn as APPROVALS_PENDING_TAG, j as ApprovalDecisionErrors, A as ApprovalErrors, E as ApprovalExpired, O as ApprovalForbidden, C as ApprovalNotFound, D as ApprovalNotPending, T as ApprovalRejected, S as ApprovalRequired, w as ApprovalSelfApproval, k as ApprovalUnavailable, Ae as AuthMiddleware, x as BusinessRuleViolation, Rn as CONNECTIONS_LIST_TAG, Vn as CONNECTION_DISCONNECT_TAG, zn as CONNECTION_START_TAG, Bn as CONNECTION_SUBMIT_TOKEN_TAG, qn as ConnectionHandshakeFailed, ce as ConnectionInfo, i as ConnectionInfoMiddleware, Q as ConnectionKind, Kn as ConnectionKindMismatch, Wn as ConnectionNotDeclared, Un as ConnectionState, Hn as ConnectionStatus, Gn as ConnectionSubjectRequired, Pn as ConstraintViolation, r as DEFAULT_SCOPE_CACHE_MAX_ENTRIES, ie as DEFAULT_SCOPE_CACHE_TTL_MS, It as EVENT_ROUTE_SEP, Nt as EventKeyInvalid, Mt as EventPayloadInvalid, Pt as EventPayloadTooLarge, be as IMPERSONATION_METADATA_KEY, St as MAX_EVENT_ENVELOPE_BYTES, $n as PROTOCOL_VERSION, M as PendingApproval, N as REACTIVITY_CHANNEL_PREFIX, c as ScopeError, Nn as ServerOnlyColumnWrite, An as StoreOperationFailed, e as Subject, ye as SubjectIdentity, re as SubjectService, jn as TableValidationFailed, Mn as TenantRowNotFound, kn as TenantScopeViolation, yn as UNDO_APPLY_TAG, vn as UNDO_LOG_TAG, bn as UNDO_REDO_TAG, s as Unauthenticated, wn as UndoConflict, Cn as UndoForbidden, xn as UndoLogEntry, Sn as UndoNotFound, X as WorkflowControlInputSchema, $t as WorkflowDomainEventRowSchema, nn as WorkflowDomainEventsInputSchema, rn as WorkflowEventDeliveriesInputSchema, en as WorkflowEventDeliveryRowSchema, qt as WorkflowParentClosePolicySchema, Qt as WorkflowRunEventRowSchema, Yt as WorkflowRunHandleSchema, tn as WorkflowRunRefSchema, J as WorkflowRunRowSchema, q as WorkflowRunStatusSchema, Zt as WorkflowRunStepRowSchema, Y as WorkflowRunTableRefSchema, Xt as WorkflowRunsInputSchema, an as WorkflowSignalInputSchema, Jt as WorkflowStartDeferralSchema, on as WorkflowUpdateInputSchema, sn as WorkflowUpdateResultSchema, _t as actionToRpc, we as advisoryResourceGuardWarning, ae as anonymousSubject, Ye as applyRowPatch, a as applyScopeDecision, Ln as approvalsDecideDescriptor, In as approvalsPendingQueryDescriptor, te as assertAuthenticated, ze as beginIdempotent, Gt as checkFrameworkCompat, De as checkGuards, me as checkGuardsEffect, ne as composeAuthStrategies, Ut as composeRpcInterceptors, Zn as connectionDisconnectDescriptor, Yn as connectionStartDescriptor, Xn as connectionSubmitTokenDescriptor, Jn as connectionsListQueryDescriptor, nt as declaredReactivityChannelKeys, V as defineAction, wt as defineEvent, B as defineMutation, Bt as definePlugin, Vt as definePluginRoute, Wt as definePluginService, z as defineQuery, dt as defineStream, qe as diffRows, xe as effectiveScopes, Ft as encodeEventKey, yt as errorTag, Dt as eventAttached, Tt as eventEnvelope, Et as eventGap, kt as eventResumePoint, Lt as eventRoute, Ot as eventStreamEvent, At as eventSubscribeInput, jt as eventToRpc, Ie as failIdempotent, ke as findAdvisoryResourceGuards, Pe as finishIdempotent, zt as formatEventRoute, he as getPolicyGuardResolver, ge as getResourceScopeResolver, ut as hasAccessDecision, oe as hasCallbackRoutes, Te as hasEffectiveScope, U as hasEnforcedGuard, Se as hasScope, g as idToPath, Re as idempotencyScope, y as inputLabel, Ct as isEventDescriptor, Je as isIdKeyed, l as isOpenAccess, _e as isPolicyCheck, lt as isPolicyGuard, et as isReactivityChannel, tt as isReactivityChannelKey, Ne as isSystemSubject, st as isWireReachable, t as makeScopeCache, Be as memoryIdempotencyStore, fe as missingAccessDecision, gt as mutationToRpc, xt as normalizeDescriptor, it as normalizeSource, u as openAccessSpec, Rt as parseEventRoute, Ge as pathToId, Ht as pluginInstanceName, ot as publishReactivity, Ve as publishServerError, ht as queryToRpc, ue as rawImpersonationMark, $e as reactivityChannel, Me as requireScope, m as rowPatchOpSchema, h as rowPatchSchema, ee as scopeCacheKey, pe as setEffectiveScopes, je as setPolicyGuardResolver, se as setResourceScopeResolver, rt as sourceKeys, vt as streamToRpc, b as strictInput, le as subjectIdentity, n as subjectScopes, Le as subscribeServerErrors, v as subscriptionEvent, de as systemSubject, o as tenantScopedSubject, bt as toRpc, Qn as tsMs, at as undeclaredChannelKeys, Dn as undoApplyDescriptor, En as undoLogQueryDescriptor, On as undoRedoDescriptor, W as wireErrorUnion, mn as workflowCancelDescriptor, fn as workflowDomainEventsQueryDescriptor, pn as workflowEventDeliveriesQueryDescriptor, hn as workflowResumeDescriptor, dn as workflowRunEventsQueryDescriptor, cn as workflowRunQueryDescriptor, un as workflowRunStepsQueryDescriptor, ln as workflowRunsQueryDescriptor, gn as workflowSignalDescriptor, _n as workflowUpdateDescriptor, Fe as wsMutationIdempotencyScope };
package/dist/jwt.d.ts CHANGED
@@ -286,7 +286,7 @@ declare const Subject: Schema.Union<[Schema.Struct<{
286
286
  * Set when this caller PRESENTED a credential and it was rejected — an
287
287
  * expired token above all. Absent when they presented none.
288
288
  *
289
- * The two are the same Subject and must not be the same ANSWER. A consumer
289
+ * The two are the same Subject and must not be the same ANSWER. A deployment
290
290
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
291
291
  * strategy logged `supabase jwt expired`, the caller fell through to
292
292
  * anonymous, and the guard then refused with `missing required scope
package/dist/rest.d.ts CHANGED
@@ -176,7 +176,7 @@ declare interface GuardSpec<Input = unknown> {
176
176
  * in its own tables (a `teamMembers` row, say) registers its own tuple source
177
177
  * rather than copying data across; see `policyGuardResolver.ts`.
178
178
  *
179
- * That paragraph is here because its absence cost a consumer their access
179
+ * That paragraph is here because its absence cost a deployment their access
180
180
  * gate. This comment used to describe the resolver as "a future ReBAC /
181
181
  * `accessPolicy()` resolver" — written before the ReBAC path shipped and
182
182
  * never updated. They read the type, quoted the sentence, concluded there was
@@ -653,7 +653,7 @@ declare interface QueryCacheConfig {
653
653
  *
654
654
  * `'tenant'` exists because the other two were the only options and neither
655
655
  * fits an org-wide figure: `subject` recomputes it per person, and `global`
656
- * is not a cache but a cross-tenant leak. A consumer reported computing the
656
+ * is not a cache but a cross-tenant leak. A deployment reported computing the
657
657
  * same nine-table statistic up to 18 times for 18 employees rather than take
658
658
  * the second option, which was the correct call.
659
659
  *
@@ -897,7 +897,7 @@ declare const Subject: Schema.Union<[Schema.Struct<{
897
897
  * Set when this caller PRESENTED a credential and it was rejected — an
898
898
  * expired token above all. Absent when they presented none.
899
899
  *
900
- * The two are the same Subject and must not be the same ANSWER. A consumer
900
+ * The two are the same Subject and must not be the same ANSWER. A deployment
901
901
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
902
902
  * strategy logged `supabase jwt expired`, the caller fell through to
903
903
  * anonymous, and the guard then refused with `missing required scope
package/dist/session.d.ts CHANGED
@@ -284,7 +284,7 @@ declare const Subject: Schema.Union<[Schema.Struct<{
284
284
  * Set when this caller PRESENTED a credential and it was rejected — an
285
285
  * expired token above all. Absent when they presented none.
286
286
  *
287
- * The two are the same Subject and must not be the same ANSWER. A consumer
287
+ * The two are the same Subject and must not be the same ANSWER. A deployment
288
288
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
289
289
  * strategy logged `supabase jwt expired`, the caller fell through to
290
290
  * anonymous, and the guard then refused with `missing required scope
@@ -330,7 +330,7 @@ declare const SubjectIdentity: Schema.Union<[Schema.Struct<{
330
330
  * Set when this caller PRESENTED a credential and it was rejected — an
331
331
  * expired token above all. Absent when they presented none.
332
332
  *
333
- * The two are the same Subject and must not be the same ANSWER. A consumer
333
+ * The two are the same Subject and must not be the same ANSWER. A deployment
334
334
  * measured the cost: a user's tab outlived their IdP's token lifetime, the
335
335
  * strategy logged `supabase jwt expired`, the caller fell through to
336
336
  * anonymous, and the guard then refused with `missing required scope
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/protocol",
3
- "version": "0.42.0",
3
+ "version": "0.43.1",
4
4
  "description": "The Voltro wire + plugin contract — defineQuery/Mutation/Action/Stream, definePlugin, sessions / JWT / API-keys, and the RPC protocol.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -54,8 +54,8 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@effect/sql": "^0.52.0",
57
- "@voltro/database": "0.42.0",
58
- "@voltro/logger": "0.42.0",
57
+ "@voltro/database": "0.43.1",
58
+ "@voltro/logger": "0.43.1",
59
59
  "jose": "^6.2.8"
60
60
  },
61
61
  "peerDependencies": {