@noego/trust 0.4.0 → 0.5.0-dev.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.
Files changed (143) hide show
  1. package/README.md +962 -14
  2. package/dist/baseline-Bkav9mS0.d.ts +380 -0
  3. package/dist/chunk-7PY2Q6OX.js +3016 -0
  4. package/dist/chunk-7PY2Q6OX.js.map +1 -0
  5. package/dist/chunk-UG6D3V4M.js +6990 -0
  6. package/dist/chunk-UG6D3V4M.js.map +1 -0
  7. package/dist/chunk-XXLWC5DB.js +112 -0
  8. package/dist/chunk-XXLWC5DB.js.map +1 -0
  9. package/dist/cli/index.js +1391 -65
  10. package/dist/cli/index.js.map +1 -1
  11. package/dist/cli/wasm-worker.js +257 -0
  12. package/dist/cli/wasm-worker.js.map +1 -0
  13. package/dist/core/index.d.ts +129 -0
  14. package/dist/core/index.js +115 -0
  15. package/dist/core/index.js.map +1 -0
  16. package/dist/eslint/index.d.ts +77 -167
  17. package/dist/eslint/index.js +320 -32
  18. package/dist/eslint/index.js.map +1 -1
  19. package/dist/licenses/@jridgewell__resolve-uri/LICENSE +19 -0
  20. package/dist/licenses/@jridgewell__sourcemap-codec/LICENSE +19 -0
  21. package/dist/licenses/@jridgewell__trace-mapping/LICENSE +19 -0
  22. package/dist/licenses/JS-DEPENDENCIES.json +83 -0
  23. package/dist/licenses/balanced-match/LICENSE.md +23 -0
  24. package/dist/licenses/brace-expansion/LICENSE +23 -0
  25. package/dist/licenses/dedent-js/LICENSE +19 -0
  26. package/dist/licenses/minimatch/LICENSE.md +55 -0
  27. package/dist/licenses/scule/LICENSE +21 -0
  28. package/dist/licenses/svelte2tsx/LICENSE +21 -0
  29. package/dist/native/licenses/CARGO-DEPENDENCIES.json +479 -0
  30. package/dist/native/licenses/LICENSE-trust.txt +15 -0
  31. package/dist/native/licenses/cargo/adler2-2.0.1/LICENSE-0BSD +12 -0
  32. package/dist/native/licenses/cargo/adler2-2.0.1/LICENSE-APACHE +201 -0
  33. package/dist/native/licenses/cargo/adler2-2.0.1/LICENSE-MIT +23 -0
  34. package/dist/native/licenses/cargo/aho-corasick-1.1.5/COPYING +3 -0
  35. package/dist/native/licenses/cargo/aho-corasick-1.1.5/LICENSE-MIT +21 -0
  36. package/dist/native/licenses/cargo/autocfg-1.5.1/LICENSE-APACHE +201 -0
  37. package/dist/native/licenses/cargo/autocfg-1.5.1/LICENSE-MIT +25 -0
  38. package/dist/native/licenses/cargo/bitflags-1.3.2/LICENSE-APACHE +201 -0
  39. package/dist/native/licenses/cargo/bitflags-1.3.2/LICENSE-MIT +25 -0
  40. package/dist/native/licenses/cargo/bstr-1.13.1/COPYING +8 -0
  41. package/dist/native/licenses/cargo/bstr-1.13.1/LICENSE-APACHE +201 -0
  42. package/dist/native/licenses/cargo/bstr-1.13.1/LICENSE-MIT +21 -0
  43. package/dist/native/licenses/cargo/bumpalo-3.20.3/LICENSE-APACHE +201 -0
  44. package/dist/native/licenses/cargo/bumpalo-3.20.3/LICENSE-MIT +25 -0
  45. package/dist/native/licenses/cargo/cfg-if-1.0.5/LICENSE-APACHE +201 -0
  46. package/dist/native/licenses/cargo/cfg-if-1.0.5/LICENSE-MIT +25 -0
  47. package/dist/native/licenses/cargo/crc32fast-1.5.2/LICENSE-APACHE +202 -0
  48. package/dist/native/licenses/cargo/crc32fast-1.5.2/LICENSE-MIT +21 -0
  49. package/dist/native/licenses/cargo/defmt-1.1.1/LICENSE-APACHE +201 -0
  50. package/dist/native/licenses/cargo/defmt-1.1.1/LICENSE-MIT +25 -0
  51. package/dist/native/licenses/cargo/defmt-macros-1.1.1/LICENSE-APACHE +201 -0
  52. package/dist/native/licenses/cargo/defmt-macros-1.1.1/LICENSE-MIT +25 -0
  53. package/dist/native/licenses/cargo/equivalent-1.0.2/LICENSE-APACHE +201 -0
  54. package/dist/native/licenses/cargo/equivalent-1.0.2/LICENSE-MIT +25 -0
  55. package/dist/native/licenses/cargo/flate2-1.1.10/LICENSE-APACHE +201 -0
  56. package/dist/native/licenses/cargo/flate2-1.1.10/LICENSE-MIT +25 -0
  57. package/dist/native/licenses/cargo/globset-0.4.20/COPYING +3 -0
  58. package/dist/native/licenses/cargo/globset-0.4.20/LICENSE-MIT +21 -0
  59. package/dist/native/licenses/cargo/hashbrown-0.17.1/LICENSE-APACHE +201 -0
  60. package/dist/native/licenses/cargo/hashbrown-0.17.1/LICENSE-MIT +25 -0
  61. package/dist/native/licenses/cargo/indexmap-2.14.0/LICENSE-APACHE +201 -0
  62. package/dist/native/licenses/cargo/indexmap-2.14.0/LICENSE-MIT +25 -0
  63. package/dist/native/licenses/cargo/itoa-1.0.18/LICENSE-APACHE +176 -0
  64. package/dist/native/licenses/cargo/itoa-1.0.18/LICENSE-MIT +23 -0
  65. package/dist/native/licenses/cargo/jiff-0.2.37/COPYING +3 -0
  66. package/dist/native/licenses/cargo/jiff-0.2.37/LICENSE-MIT +21 -0
  67. package/dist/native/licenses/cargo/jiff-core-0.1.1/COPYING +3 -0
  68. package/dist/native/licenses/cargo/jiff-core-0.1.1/LICENSE-MIT +21 -0
  69. package/dist/native/licenses/cargo/jiff-tzdb-0.1.9/COPYING +3 -0
  70. package/dist/native/licenses/cargo/jiff-tzdb-0.1.9/LICENSE-MIT +21 -0
  71. package/dist/native/licenses/cargo/jiff-tzdb-platform-0.1.3/COPYING +3 -0
  72. package/dist/native/licenses/cargo/jiff-tzdb-platform-0.1.3/LICENSE-MIT +21 -0
  73. package/dist/native/licenses/cargo/log-0.4.34/LICENSE-APACHE +201 -0
  74. package/dist/native/licenses/cargo/log-0.4.34/LICENSE-MIT +25 -0
  75. package/dist/native/licenses/cargo/lzma-rust2-0.21.0/LICENSE +201 -0
  76. package/dist/native/licenses/cargo/memchr-2.8.2/COPYING +3 -0
  77. package/dist/native/licenses/cargo/memchr-2.8.2/LICENSE-MIT +21 -0
  78. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE +25 -0
  79. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE-APACHE.md +177 -0
  80. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE-MIT.md +24 -0
  81. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE-ZLIB.md +14 -0
  82. package/dist/native/licenses/cargo/num-bigint-0.4.6/LICENSE-APACHE +201 -0
  83. package/dist/native/licenses/cargo/num-bigint-0.4.6/LICENSE-MIT +25 -0
  84. package/dist/native/licenses/cargo/num-integer-0.1.47/LICENSE-APACHE +201 -0
  85. package/dist/native/licenses/cargo/num-integer-0.1.47/LICENSE-MIT +25 -0
  86. package/dist/native/licenses/cargo/num-traits-0.2.19/LICENSE-APACHE +201 -0
  87. package/dist/native/licenses/cargo/num-traits-0.2.19/LICENSE-MIT +25 -0
  88. package/dist/native/licenses/cargo/proc-macro2-1.0.107/LICENSE-APACHE +176 -0
  89. package/dist/native/licenses/cargo/proc-macro2-1.0.107/LICENSE-MIT +23 -0
  90. package/dist/native/licenses/cargo/quote-1.0.47/LICENSE-APACHE +176 -0
  91. package/dist/native/licenses/cargo/quote-1.0.47/LICENSE-MIT +23 -0
  92. package/dist/native/licenses/cargo/regex-automata-0.4.18/LICENSE-APACHE +201 -0
  93. package/dist/native/licenses/cargo/regex-automata-0.4.18/LICENSE-MIT +25 -0
  94. package/dist/native/licenses/cargo/regex-syntax-0.8.11/LICENSE-APACHE +201 -0
  95. package/dist/native/licenses/cargo/regex-syntax-0.8.11/LICENSE-MIT +25 -0
  96. package/dist/native/licenses/cargo/rustc-hash-2.1.2/LICENSE-APACHE +176 -0
  97. package/dist/native/licenses/cargo/rustc-hash-2.1.2/LICENSE-MIT +23 -0
  98. package/dist/native/licenses/cargo/ryu-js-1.0.2/LICENSE-APACHE +176 -0
  99. package/dist/native/licenses/cargo/ryu-js-1.0.2/LICENSE-BOOST +23 -0
  100. package/dist/native/licenses/cargo/serde-1.0.229/LICENSE-APACHE +176 -0
  101. package/dist/native/licenses/cargo/serde-1.0.229/LICENSE-MIT +23 -0
  102. package/dist/native/licenses/cargo/serde_core-1.0.229/LICENSE-APACHE +176 -0
  103. package/dist/native/licenses/cargo/serde_core-1.0.229/LICENSE-MIT +23 -0
  104. package/dist/native/licenses/cargo/serde_derive-1.0.229/LICENSE-APACHE +176 -0
  105. package/dist/native/licenses/cargo/serde_derive-1.0.229/LICENSE-MIT +23 -0
  106. package/dist/native/licenses/cargo/serde_json-1.0.152/LICENSE-APACHE +176 -0
  107. package/dist/native/licenses/cargo/serde_json-1.0.152/LICENSE-MIT +23 -0
  108. package/dist/native/licenses/cargo/simd-adler32-0.3.10/LICENSE.md +21 -0
  109. package/dist/native/licenses/cargo/smallvec-1.15.1/LICENSE-APACHE +201 -0
  110. package/dist/native/licenses/cargo/smallvec-1.15.1/LICENSE-MIT +25 -0
  111. package/dist/native/licenses/cargo/syn-2.0.119/LICENSE-APACHE +176 -0
  112. package/dist/native/licenses/cargo/syn-2.0.119/LICENSE-MIT +23 -0
  113. package/dist/native/licenses/cargo/syn-3.0.7/LICENSE-APACHE +176 -0
  114. package/dist/native/licenses/cargo/syn-3.0.7/LICENSE-MIT +23 -0
  115. package/dist/native/licenses/cargo/thiserror-2.0.21/LICENSE-APACHE +176 -0
  116. package/dist/native/licenses/cargo/thiserror-2.0.21/LICENSE-MIT +23 -0
  117. package/dist/native/licenses/cargo/thiserror-impl-2.0.21/LICENSE-APACHE +176 -0
  118. package/dist/native/licenses/cargo/thiserror-impl-2.0.21/LICENSE-MIT +23 -0
  119. package/dist/native/licenses/cargo/unicode-ident-1.0.26/LICENSE-APACHE +176 -0
  120. package/dist/native/licenses/cargo/unicode-ident-1.0.26/LICENSE-MIT +23 -0
  121. package/dist/native/licenses/cargo/unicode-ident-1.0.26/LICENSE-UNICODE +39 -0
  122. package/dist/native/licenses/cargo/xxhash-rust-0.8.15/LICENSE +23 -0
  123. package/dist/native/licenses/cargo/zlib-rs-0.6.8/LICENSE +19 -0
  124. package/dist/native/licenses/cargo/zmij-1.0.23/LICENSE-MIT +23 -0
  125. package/dist/native/licenses/ts-rust/LICENSE +21 -0
  126. package/dist/native/licenses/ts-rust/NOTICE.md +53 -0
  127. package/dist/native/licenses/ts-rust/licenses/Go-LICENSE.txt +27 -0
  128. package/dist/native/licenses/ts-rust/licenses/TypeScript-LICENSE.txt +55 -0
  129. package/dist/native/licenses/ts-rust/licenses/TypeScript-NOTICE.txt +405 -0
  130. package/dist/native/licenses/ts-rust/licenses/Unicode-LICENSE.txt +39 -0
  131. package/dist/native/licenses/ts-rust/licenses/vscode-languageserver-node-LICENSE.txt +18 -0
  132. package/dist/native/licenses/typescript/LICENSE.txt +55 -0
  133. package/dist/native/licenses/typescript/ThirdPartyNoticeText.txt +193 -0
  134. package/dist/native/licenses/typescript/manifest.json +105 -0
  135. package/dist/native/trust_native_wasm.wasm +0 -0
  136. package/dist/svelte2tsx/index.cjs +7064 -0
  137. package/dist/svelte2tsx/svelte-jsx-v4.d.ts +230 -0
  138. package/dist/svelte2tsx/svelte-jsx.d.ts +1492 -0
  139. package/dist/svelte2tsx/svelte-shims-v4.d.ts +290 -0
  140. package/dist/svelte2tsx/svelte-shims.d.ts +305 -0
  141. package/package.json +31 -8
  142. package/dist/chunk-YJYGTNJD.js +0 -2168
  143. package/dist/chunk-YJYGTNJD.js.map +0 -1
package/README.md CHANGED
@@ -5,6 +5,256 @@ and every `throw`, must be handled locally by a `try` whose `catch` returns `Res
5
5
  `Trust.try` / `Trust.tryAsync`). The goal is prevention. When something on the trust list causes a
6
6
  bug, remove it from the list, and the lint flags every call to it.
7
7
 
8
+ ## Concepts
9
+
10
+ The rest of this README is reference. This section is the model that holds it together; read it
11
+ first.
12
+
13
+ ### What `ok` means
14
+
15
+ `ok: true` means **the program is ok with the value**: it holds something it knows how to use. It
16
+ does **not** mean "no error happened".
17
+
18
+ `ok: false` means **not decided yet**: something failed, and no code has said what that failure
19
+ means where it now stands.
20
+
21
+ So an error can be `ok: true`. "User 7 not found", turned by a decision into a guest user, or into
22
+ `{ status: 'not_found', id: 7 }` for a screen to render, is a value the program is ok with. The
23
+ failure did not vanish; it was given a meaning. That act — turning `ok: false` into `ok: true` by
24
+ naming what each failure means — is called **deciding**. There are two forms, each with its own job:
25
+
26
+ - **`Trust.decide` decides a subset.** The kinds this code understands become `ok`; every other kind
27
+ stays a failure in the type and is passed up. Below the boundary this is almost always
28
+ *recovery*: the cache is down, read the database instead.
29
+ - **An exhaustive `switch` decides everything.** At a boundary where no failure may leave — an API
30
+ response, an IPC reply, a CLI exit — `switch (r.error.kind)` gives every kind a `case`, and a
31
+ `never` default makes the compiler prove none is missing.
32
+
33
+ Which one, and where, is settled by one question: [can this layer still answer what it was
34
+ asked?](#when-to-decide-and-when-to-pass-up)
35
+
36
+ ### A failure has a lifecycle
37
+
38
+ ```
39
+ throw raw exception from code outside the trust list not a value yet
40
+ Trust.try becomes Err<{ kind: 'NotFound', id }> ok: false — a fact, named
41
+ return r passed up, unchanged, through every layer that ok: false — still undecided
42
+ cannot say what it means
43
+ Trust.translate optionally renamed for the layer above ok: false — a different fact
44
+ Trust.decide some kinds given a meaning (a fallback, a default) ok: true — for those kinds
45
+ the rest stay failures and keep moving up ok: false for the rest
46
+ switch at the edge, every kind left given a meaning ok: true — all decided
47
+ edge the decided value leaves as plain data no Result at all
48
+ ```
49
+
50
+ Each step has one visible form in the code:
51
+
52
+ | Step | Tool | What it says |
53
+ |---|---|---|
54
+ | A throw becomes a failure | `Trust.try` / `Trust.tryAsync` | "this outside call can fail, and here is the name of how" |
55
+ | A failure moves up | `if (!r.ok) return r;` | "I don't know what this means here" |
56
+ | A failure changes kind | `Trust.translate` | "below, this is `NotFound`; to my caller it is `Missing`" |
57
+ | Some failures stop | `Trust.decide` | "these kinds mean this here; the others are not mine to decide" |
58
+ | Every failure stops, at the edge | exhaustive `switch (r.error.kind)` with a `never` default | "here is what each one means to whoever receives this" |
59
+
60
+ Nothing else may catch, swallow or re-encode a failure: not a `try`, not `?? null`, not
61
+ `return false`, not `{ kind: 'failed' }`. Each of those stops a failure without saying what it
62
+ meant, so the reason is lost. The lint enforces this when `dropped-result` is on (see
63
+ [`dropped-result`](#dropped-result-every-failure-is-passed-up-or-handled)). It does not check what an
64
+ edge returns: a `Result` returned out through the edge counts as passed up, so "no `Result` crosses
65
+ the edge" is held in review.
66
+
67
+ ### Three roles
68
+
69
+ Code that holds a `Result` plays one of three roles:
70
+
71
+ - **Reporter.** Talks to the outside world (a database, a file, a socket) and reports what happened as
72
+ facts: a row, or a named failure with its context (`{ kind: 'NotFound', id }`). It never decides.
73
+ - **Translator.** Passes failures up untouched and adds its own when a fact means failure *for it*
74
+ (a lost compare-and-set race is a fact to the reporter and a failure to the code that needed to
75
+ win it). It never collapses several kinds into one: collapsing is deciding.
76
+ - **Decider.** Knows what a failure means where it stands and decides it. Any layer may decide a kind
77
+ it can recover from with `Trust.decide` (the cache failed → read the database); what it cannot
78
+ recover from it passes up. The edge is the decider of last resort and decides everything that is
79
+ left with an exhaustive `switch`.
80
+
81
+ ### When to decide, and when to pass up
82
+
83
+ A failure is decided by the first layer that can **still answer the question it was asked**. Every
84
+ other layer passes it up. Two questions settle almost every case:
85
+
86
+ 1. **After I handle this, does my caller still get what it asked for?**
87
+ Yes → decide it here. No → pass it up.
88
+ 2. **Is there anyone above me to pass it to?**
89
+ No → this is a boundary: decide every kind, with the `switch`.
90
+
91
+ **Decide when the failure does not change your answer.** The cache is unavailable → read the
92
+ database. The primary host times out → try the replica. The config file is missing → use the
93
+ defaults. The caller asked for a profile and gets a profile; the failure changed *how* the answer
94
+ was produced, not *what* it is. This is recovery, and it is the normal reason a layer below the
95
+ boundary decides. The recovering layer is the decider, so it is the one that logs the cause (once).
96
+
97
+ **Pass up when the failure changes the answer.** The profile does not exist. No fallback produces
98
+ one, and what "no profile" means — a 404, "create one", "skip this row", "show a placeholder" —
99
+ depends on who asked. The service does not know that; the caller might; the boundary must. A layer
100
+ that turns this into `null`, `false` or a default has not decided, it has guessed on the caller's
101
+ behalf.
102
+
103
+ ```ts
104
+ // A service: recovers from the cache, passes the database's failures up.
105
+ async function profile(id: number) {
106
+ const cached = Trust.decide(await cache.get(id), {
107
+ CacheUnavailable: (f) => {
108
+ log.warn('profile cache unavailable, reading database', { id, cause: f.cause }); // decided here, logged here
109
+ return null;
110
+ },
111
+ CacheMiss: () => null,
112
+ });
113
+ if (cached.value) return Result.ok(cached.value);
114
+ return db.profiles.get(id); // Err<NotFound> | Err<QueryFailed>: not this layer's to decide
115
+ }
116
+
117
+ // The boundary: nobody is left to ask, so every kind becomes an answer.
118
+ async function handleGetProfile(req: Request) {
119
+ const found = await profiles.profile(req.params.id);
120
+ if (!found.ok) {
121
+ switch (found.error.kind) {
122
+ case 'NotFound': return reply(404, { error: 'profile not found', id: found.error.id });
123
+ case 'QueryFailed':
124
+ log.error('profile read failed', { cause: found.error.cause });
125
+ return reply(503, { error: 'try again later' });
126
+ default: {
127
+ const unhandled: never = found.error;
128
+ return unhandled;
129
+ }
130
+ }
131
+ }
132
+ return reply(200, found.value);
133
+ }
134
+ ```
135
+
136
+ The only grey area is a method whose contract already includes absence: "the latest message, *if
137
+ any*" answers `null` to not-found because `null` is what the caller asked for. "Message 42" does
138
+ not. Read the method's question, not the failure's name.
139
+
140
+ **At the boundary, decide everything.** An HTTP or IPC reply, a CLI exit code, a UI event handler,
141
+ a scheduled job with no caller: there is no one left to pass a failure to. The boundary says what
142
+ every kind means — a status, a message, a retry, a log line and nothing — and returns plain data.
143
+ Returning a `Result` from a boundary is not a decision; it is hoping someone else will make one, and
144
+ no one is there. The exhaustive `switch` with the `never` default is the form, because it is the
145
+ only one that makes "every kind" a compile-time fact.
146
+
147
+ ### The `ok` path: keep the `Result` until the boundary
148
+
149
+ The same rule fixes what the success path looks like. Taking the value out of a `Result` for good —
150
+ returning `Profile` where you held `Result<Profile, …>` — is legitimate only where every failure has
151
+ been decided, and that is the boundary. Everywhere else, **return the `Result`, ok or not.**
152
+
153
+ ```ts
154
+ // A service that needs the value to continue reads it, and still returns a Result.
155
+ async greeting(id: number) {
156
+ const profile = await this.profiles.get(id);
157
+ if (!profile.ok) return profile; // failures pass up first
158
+ return Result.ok(`Hello, ${profile.value.name}`); // the value, used, re-wrapped
159
+ }
160
+ ```
161
+
162
+ - Reading `r.value` after `if (!r.ok) return r;` is fine: the failure has already left. What is not
163
+ fine is the function's *return type* dropping the `Result`.
164
+ - `return r` when the value is exactly what your caller asked for (it carries the value and the
165
+ failures together); `Result.ok(newValue)` when this function changes the value.
166
+ - A function that returns a plain value from a `Result` has decided every failure, so it is a
167
+ boundary. If it is a service, a helper, a repository composer — not a boundary — it has invented
168
+ one in the middle of the program: its callers get a value that may be a guess (an empty profile,
169
+ a default name) with no way to tell, and the kinds the lint was following stop dead there. Most
170
+ of a program is below the boundary, so most of a program returns `Result`.
171
+ - A boundary is defined by "there is no one above me to return to", not by the layer's name. A
172
+ controller usually; but a scheduled job, an event listener, a queue consumer, a `main` are
173
+ boundaries inside the application too. Each decides everything and returns plain data (or
174
+ nothing); everything beneath them returns `Result`.
175
+
176
+ ### The edge decides everything that is left
177
+
178
+ Every program has an **edge**: the place where values leave it — an HTTP handler, an IPC controller,
179
+ a CLI's `main`, a public library function. `Result` is an internal contract; it does not cross the
180
+ edge. The edge is the last decider: it handles **every** kind still possible and returns plain data.
181
+
182
+ The edge decides with an exhaustive `switch`. Narrow with `if (!r.ok)`, give every kind a `case`, and
183
+ end with a `default` that assigns the failure to `never`. An API response handler, for example:
184
+
185
+ ```ts
186
+ const found = await accounts.get(id);
187
+ if (!found.ok) {
188
+ switch (found.error.kind) {
189
+ case 'NotFound':
190
+ return { status: 'not_found' as const, id: found.error.id }; // found.error narrowed to NotFound
191
+ case 'ConnectionFailed':
192
+ log.error('account read failed', { cause: found.error.cause }); // logged once, by the decider
193
+ return { status: 'unavailable' as const };
194
+ default: {
195
+ const unhandled: never = found.error; // a new kind below stops this compiling
196
+ return unhandled;
197
+ }
198
+ }
199
+ }
200
+ return found.value; // plain data: the account, or one of the two statuses
201
+ ```
202
+
203
+ - The `never` default is what makes the switch exhaustive: it compiles only while every kind has a
204
+ `case`. It is required, and it holds only the `never` check — a fallback value, a log or a throw
205
+ there would absorb a kind nobody decided.
206
+ - Every `case` ends in `return` with a value: no fall-through between kinds (unless the project
207
+ enables `noFallthroughCasesInSwitch`, the compiler does not catch a forgotten `return`), and no
208
+ empty `case`. Kinds that mean the same thing may stack their labels (`case 'A': case 'B': return …`).
209
+ - `dropped-result` follows the switch: each `case 'Kind':` handles that kind, and a kind no `case`
210
+ names is still reported. It does not check that the `default` is present or that a `case` returns
211
+ a non-void value; those are held in review.
212
+
213
+ `Trust.decide` is not the edge's tool. Its job is a **subset**: below the edge, a layer that can
214
+ recover from some kinds decides those and passes the rest on (the `profile` service above). What
215
+ `decide` leaves is a new value with fewer kinds, followed the same way: passed up, decided by another
216
+ `decide`, or decided in full by the edge's `switch`. A `decide` that happens to name every kind does
217
+ compile to a plain `Ok`, but at an edge write the `switch`: it says "this is where every failure
218
+ ends".
219
+
220
+ For both forms:
221
+
222
+ - A handler (a `case` or a `decide` handler) returns what the failure means to the receiver, never
223
+ `Result.err(...)`. A handler that returns an `Err` has decided nothing; it hands the receiver an
224
+ `ok: false` it cannot act on. `decide` rejects a handler that returns `undefined` / `void`; for a
225
+ `case`, review does.
226
+ - The success value and the handlers' values come out of the edge as one union. Only a failure's
227
+ `kind` is required to be a literal; what a handler returns is ordinary data. If the receiver needs
228
+ to tell outcomes apart by type, give the handlers' values a field it can narrow on — note that
229
+ handler return values are not kept literal (`status: 'not_found'` infers as `string`), so write
230
+ `as const` where a literal type matters.
231
+ - Throwing at the edge is the exception, not the rule: when an API's contract is exceptions, the edge
232
+ turns the decided failure into one, under `//trust:accept <reason>`.
233
+
234
+ ### Only real failure points return `Result`
235
+
236
+ A `Result` is a promise to the caller that something can go wrong at runtime. Code that cannot fail
237
+ returns its value:
238
+
239
+ - An origin on the `trust` list cannot fail by definition. Resolving an instance from a DI container,
240
+ logging, a pure computation: call it and use the value. Wrapping it in `Trust.try` invents a failure
241
+ that never happens, and every caller must unwrap it for nothing (`redundant-guard` reports it).
242
+ - Programmer errors at startup (a missing registration, a misconfigured container) are not failures a
243
+ caller can handle. They fail loudly on first run; they are not `Result`s.
244
+ - What remains — I/O, a database, parsing data from outside, a child process — returns `Result`.
245
+
246
+ If a trusted origin turns out to fail in practice, take it off the `trust` list: the lint then
247
+ requires the guard at every call, and the failure enters the lifecycle above.
248
+
249
+ ### Kinds are the vocabulary
250
+
251
+ - A failure is a plain object with a literal `kind` and the context the decider will need
252
+ (`{ kind: 'NotFound', id }`, not `{ kind: 'NotFound' }`, and never a bare string or `Error`).
253
+ - Return types stay inferred, so the set of kinds flows from the reporter to the edge with no
254
+ hand-written union to drift. Change a kind below and every decider that named it goes red.
255
+ - Name a kind for what happened (`account_not_found`, `write_failed`), not for what to do about it.
256
+ What to do is the decider's job.
257
+
8
258
  ## Runtime: `@noego/trust`
9
259
 
10
260
  Zero imports, safe in any bundle. Two namespaces:
@@ -13,7 +263,7 @@ Zero imports, safe in any bundle. Two namespaces:
13
263
  |---|---|
14
264
  | `Result.ok(value)` / `Result.err(failure)` | make a result |
15
265
  | `Trust.try(fn, onError)` / `Trust.tryAsync(fn, onError)` | the only boundary that may catch a throw |
16
- | `Trust.decide(r, handlers)` | the only place a failure may stop |
266
+ | `Trust.decide(r, handlers)` | decides a subset of kinds into `ok`; the kinds it does not name stay failures. At the edge, every kind is decided with an exhaustive `switch` instead (see [The edge decides everything that is left](#the-edge-decides-everything-that-is-left)) |
17
267
  | `Trust.translate(r, mappers)` | the only place a failure may change kind |
18
268
 
19
269
  ```ts
@@ -29,8 +279,10 @@ Rules:
29
279
 
30
280
  1. A failure is an object with a literal `kind`: `{ kind: 'NotFound', id }`. Write it as a plain object literal; the
31
281
  kind stays literal without `as const`.
32
- 2. On failure either `return r` (pass it up) or `Trust.decide` it. Nothing else may stop a failure.
33
- 3. A `decide` handler returns a value (never `undefined`/`void`); that value says what replaced the failure.
282
+ 2. On failure either `return r` (pass it up) or decide it: `Trust.decide` for the kinds this code
283
+ understands (the rest stay failures), or, at the edge, an exhaustive `switch (r.error.kind)` ending in a
284
+ `never` default for every kind. Nothing else may stop a failure.
285
+ 3. A `case` or `decide` handler returns a value (never `undefined`/`void`); that value says what replaced the failure.
34
286
  4. Leave fallible functions' return types inferred so the failure kinds flow to the caller.
35
287
  5. A thrown error from outside code becomes a named failure in `Trust.try` / `Trust.tryAsync`. No other `try` is needed.
36
288
 
@@ -59,6 +311,56 @@ Handlers and mappers are synchronous: async handlers are not supported.
59
311
  A single declared failure whose `kind` is a union (`{ kind: 'missing' | 'locked'; path: string }`) is treated as one
60
312
  failure per kind, so each handler narrows to its own kind.
61
313
 
314
+ ### New in 0.5.0
315
+
316
+ Upgrading from 0.4.0 changes no finding: the two new rules are **off** until a project turns them on, so
317
+ `trust check`, `trust baseline` and the ESLint `typedConfig` report exactly what 0.4.0 reported.
318
+
319
+ - **`type-claim`** reports every place a type is claimed instead of proven: a narrowing `as`, `x!`, `any` in a
320
+ typed position, a written type predicate, a caller-chosen generic return
321
+ (see [`type-claim`](#type-claim-types-that-are-claimed-not-proven)).
322
+ - **`untrusted-value`** makes type trust opt-in: a value whose type was declared by an origin that is not
323
+ type-trusted (a call's return, a callback parameter the outside fills, a property or global it declares) may
324
+ only be validated, kept as `unknown`, or tested by a built-in check
325
+ (see [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)).
326
+ - **`trust_type` / `distrust_type`**: a second pair of origin lists in trust.config.json, separate from
327
+ `trust` / `distrust`, saying which origins declare types that are true at runtime (`"trust_type": ["zod",
328
+ "node:path"]`). They inherit through `extend` and resolve like `trust` / `distrust`.
329
+ - **`//trust:validator_function`**: a comment that marks a function as a validator. Passing an untrusted value
330
+ to it is allowed, what it returns is trusted, and claims inside it are not reported
331
+ (see [Validators](#validators-trustvalidator_function)).
332
+ - **`//trust:accept <reason>`**: a comment directly above a statement that accepts its throw, untrusted call or
333
+ promise finding, with the reason why (see [Accepted failure paths](#accepted-failure-paths-trustaccept-reason)).
334
+ - **`trust refactor`** prints the order to fix files in: waves of files whose imports are already done, leaves
335
+ first, with circular-import groups kept together (see [`trust refactor`](#trust-refactor-the-order-to-refactor-in)).
336
+
337
+ Turn the new rules on per project with `rules` in trust.config.json:
338
+
339
+ ```json
340
+ {
341
+ "extend": "default",
342
+ "rules": { "type-claim": "on", "untrusted-value": "on", "untrustedCallbacks": "inline" }
343
+ }
344
+ ```
345
+
346
+ - `"type-claim"` / `"untrusted-value"` / `"dropped-result"`: `"on"` or `"off"` (default `"off"`). `dropped-result`
347
+ (see [`dropped-result`](#dropped-result-every-failure-is-passed-up-or-handled)) reports every place a `Result` that
348
+ can still fail is dropped instead of returned or handled. `redundant-guard`
349
+ (see [`redundant-guard`](#redundant-guard-a-guard-around-code-that-cannot-fail)) reports a guard around code that
350
+ cannot fail. Both use `"on"` / `"off"` like the others.
351
+ - `"untrustedCallbacks"`: which callback parameters `untrusted-value` treats as untrusted: `"inline"` (default: a
352
+ parameter of a function written inline where an origin that is not type-trusted calls it, e.g.
353
+ `ws.on('message', (data) => …)`), `"off"` (none), or `"all"` (`"inline"`, plus every function handed to such
354
+ an origin some other way, judged at the hand-off: see
355
+ [Callbacks not written inline](#callbacks-not-written-inline-untrustedcallbacks-all)).
356
+ - Each key inherits through `extend` on its own, like the other keys: the nearest file that sets it wins. A
357
+ shared base config can turn a rule on for every project that extends it, and one project can still turn it off.
358
+
359
+ The CLI (`trust check`, `trust baseline`, `trust explain`, `trust refactor`) and the ESLint rules read the same
360
+ settings, so they always agree. `typedConfig` still registers `trust/type-claim` and `trust/untrusted-value`;
361
+ they report nothing while the config leaves them off. `trust explain` says when a rule is off instead of listing
362
+ its claims or values. After you turn a rule on, run `trust baseline --update` to record what it finds today.
363
+
62
364
  ### Breaking in 0.4.0
63
365
 
64
366
  `Result` is now only `{ ok, err }`. `try`, `tryAsync`, `decide` and `translate` moved to `Trust`:
@@ -72,11 +374,20 @@ An inline `err({ kind: ... })` now keeps its literal kind, so a callback returni
72
374
 
73
375
  ## Lint: `@noego/trust/eslint`
74
376
 
75
- Rules (typed linting required for `untrusted-call-must-return-result`):
377
+ Rules (typed linting required for `untrusted-call-must-return-result`, `type-claim` and `untrusted-value`):
76
378
 
77
379
  - `trust/untrusted-call-must-return-result`: calls/`new` into untrusted origins must be guarded.
78
380
  Messages: `unguarded`, `notAwaited`, `callsIgnored`, `rethrow`, `notResultErr`, `rawCatchValue`, `notAllPaths`.
79
381
  - `trust/throw-must-return-result`: every `throw` must be guarded.
382
+ - `trust/type-claim`: every place a type is claimed instead of proven (see [`type-claim`](#type-claim-types-that-are-claimed-not-proven)).
383
+ Messages are the claim kinds: `claim:as`, `claim:non-null`, `claim:any`, `claim:predicate`, `claim:generic-return`,
384
+ `unanalyzable`, and `directive` (a `//trust:` comment that marks nothing). `typedConfig` enables it with the other two.
385
+ - `trust/untrusted-value`: every use of a value whose type was declared by an origin that is not type-trusted
386
+ (see [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)). Messages: `untrusted`, and `callerChosen` for a
387
+ return type the call picked itself. `typedConfig` enables it too.
388
+
389
+ The plugin is a thin adapter: it maps ESLint's nodes to TypeScript nodes and runs the same rule code as
390
+ `trust check`, so `eslint` and `typescript-eslint` are optional peers needed only for the plugin.
80
391
 
81
392
  ```js
82
393
  // eslint.config.js
@@ -95,20 +406,51 @@ export default [
95
406
  "extend": "default",
96
407
  "trust": ["zod", { "origin": "@noego/ioc", "reason": "DI container, no I/O" }],
97
408
  "distrust": ["js:Array.from"],
409
+ "trust_type": ["zod", { "origin": "node:path", "reason": "returns plain strings" }],
410
+ "distrust_type": [],
98
411
  "passthrough": ["server/repositories/**"],
99
- "ignore": ["**/*.test.ts", "server/testing/**"]
412
+ "ignore": ["**/*.test.ts", "server/testing/**"],
413
+ "strict": ["server/services/workspace/**", "server/controller/workspace.controller.ts"],
414
+ "tsconfig": [{ "files": "ui/**", "tsconfig": "tsconfig.web.json" }]
100
415
  }
101
416
  ```
102
417
 
103
- - `extend`: a preset (`js`, `node`, `web`, `default`) or a relative path. Chains are followed.
418
+ - `extend`: a preset (`js`, `node`, `web`, `default`, `svelte`) or a relative path, or a non-empty array of them
419
+ (`"extend": ["web", "svelte"]`). Chains are followed. Array entries apply left to right: a later entry
420
+ overrides an earlier one, and the file itself overrides all of them. For `"extend": ["a", "b"]` the lookup
421
+ order is this file, then `b`'s chain, then `a`'s chain; a level both reach (`js`) is looked at once, at its
422
+ first position in that order. Settings with a single value (each `rules` key) come from the nearest level
423
+ that sets them, so `b` beats `a`. An empty array, an entry that is not a non-empty string, the same entry
424
+ twice, an unknown preset and a cycle through any entry are load errors naming the file. Presets may extend
425
+ an array of presets, never a file.
104
426
  - `trust` / `distrust`: origins. An entry covers the origin itself, its subpaths (`node:fs` covers
105
427
  `node:fs/promises`), and its members (`js:JSON` covers `js:JSON.parse`). Lookup walks from this file toward the
106
428
  root preset; the first level whose `distrust` matches makes it untrusted, so `distrust` removes inherited trust.
429
+ - `trust_type` / `distrust_type`: a second, separate pair of lists with the same origin syntax, entry shapes
430
+ (`"origin"` or `{ "origin", "reason" }`), `extend` chain and lookup. `trust` says a call into the origin cannot
431
+ fail; `trust_type` says the types the origin declares are true at runtime. Neither implies the other:
432
+ `fs.readFileSync` can throw but its `string` is true; a typed IPC payload cannot throw but its type may be
433
+ false. An origin not on the type-trust list gives untrusted values (see
434
+ [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)). Within one file an origin may not be on both
435
+ `trust_type` and `distrust_type`; it may be on `trust` and `distrust_type`. First-party code in checked files and
436
+ `@noego/trust` itself need no entry. The earlier names `typeTrust` / `typeDistrust` are rejected with an error
437
+ naming the replacement.
107
438
  - `passthrough`: files not checked inside; calls *into* them from checked code are untrusted (`local:<path>#<member>`).
108
439
  - `ignore`: files not checked inside and trusted from outside; calls into them from checked code are reported
109
440
  (`callsIgnored`) because ignoring alone silently trusts.
441
+ - `strict` (`trust check` only): globs of files that are always checked under the strict rules, with or without
442
+ the `--strict` flag. Use it to hold finished parts of the tree to the strict standard. `!negation` carves files
443
+ back out; `ignore` still wins. `trust baseline` and ESLint ignore this key.
444
+ - `tsconfig` (CLI only): an ordered list of `{ "files": <glob or globs>, "tsconfig": <path> }`. The first entry
445
+ whose globs match a file picks the tsconfig its program is built from; the path is relative to the config
446
+ file's directory. `--tsconfig` overrides it, and files no entry matches use the nearest `tsconfig.json`. A file
447
+ that maps to a missing tsconfig stops the run (exit 2) with the entry named. ESLint ignores this key.
110
448
  - Globs use ESLint flat-config semantics (minimatch, `dot: true`, `!negation`, last match wins), relative to the
111
- config file's directory, matched on realpaths. A glob matching no file is a load error.
449
+ config file's directory, matched on realpaths. A glob matching no file is reported, not fatal: the CLIs print
450
+ `trust <command>: warning: … glob "…" matches no files` and run, and `loadTrustConfig` (the ESLint route) loads
451
+ and lists it in `unmatchedGlobs`, so every entry point treats the same config the same way (a glob can match
452
+ nothing for a legitimate moment, e.g. generated files absent in a fresh worktree). Pass
453
+ `loadTrustConfig(file, { validateGlobs: true })` to make it a load error, or `false` not to check.
112
454
 
113
455
  A call is also trusted when its declared return type is `Result` / `Promise<Result>` from `@noego/trust`,
114
456
  unless its origin is explicitly distrusted. `Result.err`, `Trust.try` and `Trust.tryAsync` are recognised
@@ -116,12 +458,17 @@ by declaration, not by name.
116
458
 
117
459
  ### Presets
118
460
 
119
- | Preset | Extends | Trusts |
120
- |---|---|---|
121
- | `js` | | Pure JavaScript built-ins that cannot fail on typed input (`js:Array`, `js:Map`, `js:Math`, …), the same in every runtime. |
122
- | `node` | `js` | Node built-in APIs, audited member by member against the Node v24 source (v26 recorded). |
123
- | `web` | `js` | Nothing beyond `js` yet: browser globals have not been audited. |
124
- | `default` | `node` | Alias of `node`. |
461
+ | Preset | Extends | Trusts (cannot fail) | Type-trusts |
462
+ |---|---|---|---|
463
+ | `js` | | Pure JavaScript built-ins that cannot fail on typed input (`js:Array`, `js:Map`, `js:Math`, …), the same in every runtime. | The language built-ins whose declared types hold whenever their inputs have theirs (`js:Array`, `js:String`, `js:Map`, `js:Promise`, `js:Math`, …). |
464
+ | `node` | `js` | Node built-in APIs, audited member by member against the Node v24 source (v26 recorded). | Nothing beyond `js` yet. |
465
+ | `web` | `js` | Nothing beyond `js` yet: browser globals have not been audited. | Nothing beyond `js` yet. |
466
+ | `default` | `node` | Alias of `node`. | Alias of `node`. |
467
+ | `svelte` | | Svelte 5 runes (`svelte.$state`, `svelte.$derived`, `svelte.$effect`, `svelte.$props`, `svelte.$bindable`, `svelte.$inspect`, each with its sub-runes), `svelte.tick`, `svelte/store`, and `SvelteMap` / `SvelteSet` / `SvelteDate` / `createSubscriber` of `svelte/reactivity` (not `SvelteURL` / `SvelteURLSearchParams`: their constructors throw). | The runes that return what they are given: `$state`, `$state.raw`, `$derived`, `$derived.by`. Not `$state.snapshot` (a clone, typed by approximation) and not `$props` (declared `any`). |
468
+
469
+ `svelte` extends nothing: it is an add-on for a runtime preset, `"extend": ["web", "svelte"]` or
470
+ `["default", "svelte"]`. Runes are global functions in svelte's types, so their origins are `svelte.<rune>`
471
+ (`svelte.$state`, `svelte.$state.raw`).
125
472
 
126
473
  The `node` list trusts a call only if arguments that satisfy its TypeScript types cannot make it throw or fail
127
474
  asynchronously (rejected promise, error-first callback, an `'error'` event caused by the call). Doing I/O or
@@ -131,6 +478,15 @@ not, and neither do engine resource limits. Whole-module or whole-class entries
131
478
  was trusted, with explicit `distrust` entries for any member that can fail under a trusted class. The evidence
132
479
  for every entry is in `research/node-api/`.
133
480
 
481
+ Type trust is a separate audit, and so far only the `js` preset (and `svelte`, for its runes) has one: built-ins that carry their types from
482
+ what they are given (an array of users maps over users) or return what the specification says. It leaves out
483
+ `js:JSON` (`parse` returns `any`; `stringify` is declared `string` but returns `undefined` for `undefined`, a
484
+ function or a symbol), the `groups` of a regular-expression match, and every DOM / web API except the timer
485
+ handles of `js:setTimeout` / `js:setInterval` (`js:fetch`, `js:Response`, `js:MessageEvent`, `js:Location`, …):
486
+ what those hold comes from outside. Node APIs are not type-trusted by any preset; add the ones a project relies
487
+ on to its own `trust_type` (`node:path`, `node:fs`, …). A config with no `extend` type-trusts nothing, not even
488
+ `js:Array`.
489
+
134
490
  A project with several runtimes gives each area its own trust config:
135
491
 
136
492
  ```js
@@ -162,7 +518,599 @@ The old `builtin:` and `node.` prefixes are rejected at load time with the repla
162
518
  ## CLI: `trust`
163
519
 
164
520
  ```sh
165
- trust explain server/services/foo.ts:42[:7] # origin + verdict for each call on that line
521
+ trust explain server/services/foo.ts:42[:7] # origin + throw-trust and type-trust verdict for each call on that line,
522
+ # why a type claim there is one, and where an untrusted value comes from
166
523
  trust baseline server --update # write trust-baseline.json (file + rule + origin -> count)
167
524
  trust baseline server # exit 1 when any count grows
525
+ trust baseline server --tsconfig tsconfig.json # one tsconfig for all files, as in trust check
526
+ trust check server # no baseline, no ESLint: exit 1 on any trust finding
527
+ trust check ui --tsconfig tsconfig.web.json # one tsconfig for all files instead of the mapped / nearest one
528
+ trust check server --strict # also fail on written return types
529
+ trust check ui --config /tmp/trust.json --root . # a config outside the project; its paths resolve against --root
530
+ trust refactor server # the order to fix the files with findings in: waves, leaves first
531
+ trust refactor server ui --json # the same plan as JSON: { "waves": [["a.ts", ["b.ts", "c.ts"]], ["d.ts"]], ... }
532
+ ```
533
+
534
+ `trust check` uses the Rust engine automatically, with the bundled Wasm engine as fallback.
535
+ It needs neither ESLint nor an installed TypeScript package. TypeScript 5.9.3 standard-library declarations
536
+ are copied and embedded when the engine is built; they are not chosen from the checked project at runtime.
537
+ The experimental `--rs` and `--go` flags have been removed.
538
+
539
+ Every rule, including the opt-in `type-claim`, `untrusted-value`, `dropped-result` and `redundant-guard`,
540
+ runs in the engine. The TypeScript implementation in `src/core` stays the reference: differential tests
541
+ (`test/native-check.test.ts`, `test/native-opt-in.test.ts`) run the fixtures and the shared rule-case corpus
542
+ through both and compare whole findings (file, position, rule, message, severity). Two things keep the
543
+ output independent of the compiler: type text in messages is printed in a canonical member order
544
+ (`src/core/type-text.ts`), and when a receiver or member is a union the declaration with the smallest
545
+ origin is the one reported, on both sides. See [native/RELEASE.md](native/RELEASE.md) for the release process.
546
+
547
+ The check walks the given files and directories for `.ts`/`.tsx` (skipping `node_modules`, `dist`,
548
+ `.d.ts`) and skips the config's `ignore` zone. Exit codes are 0 for clean or warnings only,
549
+ 1 for trust violations, and 2 when setup, parsing or the engine fails. `--perf` adds three optional
550
+ warnings: `perf-delete-property`, `perf-object-as-map`, and `perf-prototype-mutation`. It does not
551
+ include a sparse-array rule. Warnings teach the tradeoff and never change the exit code.
552
+ `--json` emits one object with `findings` (each has `severity: "error" | "warning"`), setup `errors`,
553
+ configuration `warnings`, and a `summary` on success.
554
+
555
+ Each file is type-checked with `--tsconfig`
556
+ when given, else the tsconfig of the first matching `tsconfig` entry in the trust config, else the nearest
557
+ `tsconfig.json` above it (one program per tsconfig, rooted at the checked files plus the tsconfig's `.d.ts`
558
+ files). Map files whose ESLint tsconfig is not the nearest one (e.g. `ui/**` linted with `tsconfig.web.json`)
559
+ in the config, and `trust check server ui` needs no flags. `trust explain` resolves its file the same way.
560
+ `--root <dir>` (all three commands) resolves the config's globs, `tsconfig` paths and baseline keys against
561
+ `<dir>` instead of the config file's directory. `trust refactor` takes `--tsconfig` and `--root` the same way.
562
+
563
+ `trust baseline` still uses the TypeScript package (no ESLint, no env flag), as do `trust explain`,
564
+ `trust refactor` and the public core API. It finds files exactly as `trust check`
565
+ does, takes `--tsconfig <path>` the same way, and compares the core's findings with `trust-baseline.json`.
566
+ With paths (`trust baseline ui`), the run speaks only for the files it checked: only their entries are reported
567
+ as having fewer findings, and `--update` rewrites only their entries, keeping every other file's entries as they
568
+ are. Files skipped as ignored and files outside the paths never count. With no paths the run covers the whole
569
+ tree: every entry without its findings counts, and `--update` writes only the current findings (this is how
570
+ entries of deleted files go away).
571
+
572
+ Besides the two trust rules it counts two promise rules:
573
+
574
+ - `floating-promise` (origin `unhandled`): a promise expression statement that is not awaited, assigned, or
575
+ handled with `.catch(...)` / `.then(onFulfilled, onRejected)`. Prefix it with `void` to run it on purpose
576
+ without waiting.
577
+ - `misused-promise`: a promise used as a condition (`condition`: `if`, `while`, ternary, `!`, `&&`/`||`/`??`), or
578
+ an async callback passed where a void-returning function is expected (`void-callback`, e.g. `forEach`,
579
+ `setTimeout`).
580
+
581
+ Baseline entries under the old `@typescript-eslint/no-floating-promises` / `@typescript-eslint/no-misused-promises`
582
+ ids become stale (nothing reports those ids anymore); one `trust baseline --update` clears them and records the new
583
+ rule ids.
584
+
585
+ ### `type-claim`: types that are claimed, not proven
586
+
587
+ The trust rules make every failure explicit; `type-claim` does the same for types. It reports every place where
588
+ a type is asserted instead of inferred or checked, so the list can be baselined and only shrink. `trust check`,
589
+ `trust baseline` and the ESLint plugin (`trust/type-claim`) run the same rule code. Each finding's origin is the
590
+ kind of claim, so the baseline groups them per file and kind:
591
+
592
+ | origin | what is reported | not reported |
593
+ |---|---|---|
594
+ | `claim:as` | `x as T` / `<T>x` when the type of `x` is not assignable to `T` (`unknown as User`, `string \| undefined` as `string`, a downcast) | a widening assertion (`admin as User`, `x as unknown`), `as const`, `satisfies` |
595
+ | `claim:non-null` | `x!` | `x ?? fallback`, a check that narrows |
596
+ | `claim:any` | a written `any` (also `as any`); a value of type `any` assigned, passed or returned where another type is expected; a member of an `any` value used, or the value called | `any` kept in an unannotated variable, or handed to `unknown` |
597
+ | `claim:predicate` | a written type predicate or assertion signature (`x is T`, `asserts x is T`, `asserts x`): the compiler does not check the body against it | a predicate the compiler infers from the body (no annotation) |
598
+ | `claim:generic-return` | a call whose type parameter appears only in the return type, so the caller picks the result type: `parse<User>(text)`, `const u: User = parse(text)`, `db.query<Row>(sql)`. Reported whatever the callee's origin, unless a `trust_type` entry of your own config covers it (see [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)) | nothing chosen (the type parameter stays `unknown`, or the declaration's own default/constraint); a type parameter that also types a parameter; `new Map<K, V>()`; a callee whose own body proves the type for every choice (it has a body and no claim in it: `function none<T>(): T[] { return []; }`, a failure constructor returning `Result<T, E>`) |
599
+ | `unanalyzable` | a node the analyzer cannot type: a value or type that does not resolve (missing import, unknown name), a generic call whose declaration cannot be read, a TypeScript too old to answer (assignability needs 5.4). Never a silent pass | |
600
+
601
+ A member chain on an `any` value is one finding (at its first link), and `x as any` is one finding (at the
602
+ keyword) however the result is used. A cast from `any` (`JSON.parse(text) as User`) is `claim:any`, not
603
+ `claim:as`: `any` is assignable to everything, so the claim is the `any`. A declaration without a body (a
604
+ `.d.ts`, an overload or interface signature) proves nothing, so a caller-chosen generic declared that way is
605
+ a `claim:generic-return` unless your own config type-trusts its origin.
606
+
607
+ The only place a claim is allowed is inside a validator, a function marked `//trust:validator_function` (see
608
+ [Validators](#validators-trustvalidator_function)). Adopt the rule like the others: `trust baseline --update`
609
+ records today's claims, and from then on only new ones fail. `trust explain <file>:<line>` prints the kind and
610
+ the reason:
611
+
612
+ ```text
613
+ server/users.ts:73 (zone: checked)
614
+
615
+ 73:10 value as T
616
+ claim: claim:as (rule type-claim)
617
+ why: Type assertion claims "unknown" is "T", but "unknown" is not assignable to "T": nothing proves it. Narrow or validate the value instead.
618
+ ```
619
+
620
+ The CLI commands (`check`, `baseline`, `explain`, `refactor`) always check `.svelte` components,
621
+ including script and template expressions, using in-memory conversion and original source positions.
622
+ Svelte is optional: `@noego/trust` declares no dependencies, so a TypeScript-only project never installs
623
+ `svelte`. When `.svelte` files are checked, `svelte` (and `typescript`) must be installed in the project;
624
+ trust converts components with its own bundled `svelte2tsx`, which is loaded only then. A missing `svelte`,
625
+ conversion errors and collisions with a real adjacent `.svelte.ts` fail the run; components are never skipped.
626
+ Preprocessors are not run. Real `.svelte.ts` rune modules remain ordinary TypeScript files.
627
+
628
+ Add `"extend": ["web", "svelte"]` (or `["default", "svelte"]`) to trust Svelte APIs;
629
+ conversion does **not** automatically apply the preset. Only generated snippet-render wrappers are trusted,
630
+ not their argument expressions or snippet bodies. `createContext` remains untrusted, including its setter
631
+ (the same declaration origin): use `setContext` or a justified `//trust:accept` directive.
632
+
633
+ Not covered: the ESLint `.svelte` integration, lifecycle cleanup guards, and TypeScript's own unsound
634
+ corners (method bivariance, array covariance).
635
+
636
+ #### Validators: `//trust:validator_function`
637
+
638
+ A claim is allowed in one place: a **validator**, a function that checks an `unknown` value and returns it
639
+ typed. Mark it with the directive on the line directly above its declaration:
640
+
641
+ ```ts
642
+ import { Result } from '@noego/trust';
643
+
644
+ //trust:validator_function
645
+ export function parseUser(input: unknown) {
646
+ if (typeof input !== 'object' || input === null || typeof (input as { name?: unknown }).name !== 'string') {
647
+ return Result.err({ kind: 'invalid', issues: ['name must be a string'] });
648
+ }
649
+ return Result.ok(input as User);
650
+ }
651
+
652
+ const parsed = parseUser(payload); // payload: unknown
653
+ if (!parsed.ok) return parsed; // Err<{ kind: 'invalid'; issues: string[] }>
654
+ parsed.value; // User
655
+ ```
656
+
657
+ From there on that function is not questioned:
658
+
659
+ - No claim inside it is a finding: `as`, `!`, `any`, a written type predicate and a caller-chosen generic are
660
+ allowed in its signature, its body and the functions nested in it. Remove the directive and every one of
661
+ them is a finding again.
662
+ - Its return type is trusted at every call site: a generic validator (`validate<T>(input: unknown)`) is not a
663
+ `claim:generic-return` for its callers.
664
+ - Passing an untrusted value into it is the sanctioned exit from `unknown`. A validator returns `Result`, so a
665
+ failed validation is an ordinary failure kind (`{ kind: 'invalid', issues }`) that callers return or decide
666
+ like any other; a validator never throws.
667
+
668
+ The directive is recognised on a function declaration, a method (class or object literal), and an arrow or
669
+ function expression assigned to a `const`, exported or not (a space after `//` is fine). It must be the last
670
+ comment on the line directly above the declaration's first token: after any JSDoc, with no blank line between.
671
+ Every other `//trust:` comment, except `//trust:accept` (see
672
+ [Accepted failure paths](#accepted-failure-paths-trustaccept-reason)), is a finding (`type-claim`, origin `directive`): a misspelling
673
+ (`//trust:validator`), extra words after it, a block comment, or a directive above a blank line, a `let`, a
674
+ class, a class property, at the end of a block or a file, or alone inside an empty body, class, object, array,
675
+ type literal or parameter list. A typo cannot silently leave a function unmarked or mark the wrong thing.
676
+
677
+ The directive is a human decision, like a trust-list entry: trust does not inspect what a marked function does,
678
+ and a wrong validator means wrong trust. The recommended way to write one is to link the schema to the type,
679
+ so the compiler keeps them in agreement. With [AJV](https://ajv.js.org/), `JSONSchemaType<T>` rejects a schema
680
+ that does not match `T` (trust has no dependency on AJV and does not check schemas; this is the pattern):
681
+
682
+ ```ts
683
+ import Ajv, { type JSONSchemaType } from 'ajv';
684
+ import { Result } from '@noego/trust';
685
+
686
+ interface User {
687
+ name: string;
688
+ age?: number;
689
+ role: 'admin' | 'member';
690
+ }
691
+
692
+ // Does not compile when a property of User is missing, misnamed or mistyped here.
693
+ const userSchema: JSONSchemaType<User> = {
694
+ type: 'object',
695
+ properties: {
696
+ name: { type: 'string' },
697
+ age: { type: 'integer', nullable: true },
698
+ role: { type: 'string', enum: ['admin', 'member'] },
699
+ },
700
+ required: ['name', 'role'],
701
+ additionalProperties: false,
702
+ };
703
+ const isUser = new Ajv().compile(userSchema);
704
+
705
+ //trust:validator_function
706
+ export function parseUser(input: unknown) {
707
+ if (!isUser(input)) return Result.err({ kind: 'invalid', issues: isUser.errors ?? [] });
708
+ return Result.ok(input);
709
+ }
168
710
  ```
711
+
712
+ `JSONSchemaType<T>` patterns: an optional property (`age?: number`) is `nullable: true` and left out of
713
+ `required`; `T | null` is `{ type: ..., nullable: true }`; a union of object shapes is `oneOf` / `anyOf` with
714
+ each member written out; a `Date` or a class instance has no JSON form, so validate the wire shape (an ISO
715
+ string) and convert after the check.
716
+
717
+ #### Accepted failure paths: `//trust:accept <reason>`
718
+
719
+ Some failures are meant to escape: the one public edge where internal `Result` failures become the exceptions
720
+ an API promises, or a fallback that is the design. Accept such a failure path with the directive on the line
721
+ directly above **the statement**, the `throw` itself or the statement holding the call, never above its
722
+ function:
723
+
724
+ ```ts
725
+ export function raise(failure: Failure): never {
726
+ //trust:accept public API contract: callers get these error classes
727
+ throw toError(failure);
728
+ }
729
+
730
+ try {
731
+ //trust:accept runtimes without async_hooks fall back to synchronous propagation
732
+ const hooks =
733
+ process.getBuiltinModule?.('node:async_hooks') ??
734
+ require('node:async_hooks');
735
+ // ...
736
+ } catch {
737
+ // fallback
738
+ }
739
+ ```
740
+
741
+ - It accepts the findings of `throw-must-return-result`, `untrusted-call-must-return-result`,
742
+ `floating-promise` and `misused-promise` that belong to that statement, and nothing else. A finding belongs
743
+ to the innermost statement around it in the same function: a statement nested in a block of the accepted one
744
+ (an `if` or loop body) is one of its own, and so is everything inside a function or class written in it
745
+ (`const f = () => risky();` accepts nothing). Never the enclosing function, never a sibling statement.
746
+ - Never a type claim: validators are the only way out there.
747
+ - The reason is required: it is the human decision, like a trust-list entry. Nothing checks it.
748
+ - Placement is as strict as the validator directive's: the last comment on the line directly above the
749
+ statement's first token, no blank line between. The statement holds expressions of its own: an expression,
750
+ `const`/`let`/`var`, `return`, `throw`, `if`, a loop, `switch`, `export default`. A function, class or other
751
+ declaration, a block or a `try` is not one.
752
+
753
+ An accept that accepts nothing is a finding (`throw-must-return-result`, origin `directive`), whether or not
754
+ `type-claim` is on: no reason, a block comment, above a blank line, above a declaration or anything that is not
755
+ such a statement, or above a statement with nothing to accept (stale). A misspelling (`//trust:acept`) is no
756
+ accept: it accepts nothing, the finding below it stays, and `type-claim` (when on) reports the comment like any
757
+ unknown directive. `trust check`, `trust baseline`, `trust explain` and the ESLint rules decide it with the same
758
+ code; without type information the ESLint rule cannot tell a stale accept and does not report it.
759
+ `trust explain` lists each accepted finding on the line with its reason:
760
+
761
+ ```text
762
+ 91:5 throw toError(failure);
763
+ accepted: throw-must-return-result (throw) by //trust:accept on line 90
764
+ reason: public API contract: callers get these error classes
765
+ finding: `throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Trust.try/tryAsync.
766
+ ```
767
+
768
+ `--strict` adds `no-written-return-type`: a function, method, arrow or getter with a body must not spell out its
769
+ return type; the inferred type is the truth. Bodiless signatures,
770
+ type predicates (`x is Foo`) and assertion signatures (`asserts x`) are exempt. The flag makes every checked
771
+ file strict for that run; the config's `strict` globs make matching files strict on every `trust check` run
772
+ (the summary then says `(N strict by config)`). The `ignore` list is the only way to exempt a file.
773
+
774
+ ### `untrusted-value`: type trust is opt-in
775
+
776
+ `type-claim` reports the claims written in checked code. `untrusted-value` covers the ones that arrive from
777
+ outside: a value is only as true as the type someone declared for it, and a DB row generic, a typed IPC
778
+ payload, `postMessage` data or a library `.d.ts` can all be wrong at runtime. So nothing external is
779
+ type-trusted unless a `trust_type` entry says so (see [trust.config.json](#trustconfigjson)), and a value from
780
+ anywhere else is treated like `unknown` until a validator has seen it.
781
+
782
+ A value is untrusted when the type it has was declared by an origin that is not on the type-trust list. It
783
+ enters checked code in one of these ways (the *entry*, shown by `trust explain`):
784
+
785
+ | entry | what | example |
786
+ |---|---|---|
787
+ | `return` | the result of a call / `new` into such an origin | `readConfig()`, `await fetchRow()` |
788
+ | `parameter` | a parameter of a callback whose signature such an origin declares: the outside calls it, and an annotation on the parameter is your claim | `ws.on('message', (data) => …)`, `ipcMain.handle((event, payload: Foo) => …)` |
789
+ | `read` | a property or global such an origin declares | `process.env.PORT`, `event.data`, `location.hash` |
790
+ | `generic-return` | the result of a call that picked its own return type, **even from a first-party origin or one only a built-in preset type-trusts** | `db.query<User>(sql)` |
791
+ | `catch` | a `catch` variable | `catch (error)` |
792
+ | `guard` | a value narrowed by a type guard or assertion function (`x is T`, `asserts x is T`, `asserts x`) whose signature such an origin declares: the narrowed type is that origin's claim, even when the value was declared `unknown` | `if (validateUser(input)) input.name` with `validateUser = ajv.compile(schema)`, `assertUser(input)` |
793
+
794
+ A `guard` names the origin that declares the **signature** the call resolves to, not the name it is called
795
+ through: `const validateUser = ajv.compile(schema)` is your name for AJV's `ValidateFunction<User>`, so the
796
+ origin is `ajv.ValidateFunction`, and `"trust_type": ["ajv"]` (or that member path) trusts what it narrows.
797
+ The guard counts where it holds: the branch of an `if` / `?:` / `&&` / `||` / loop its result decides, the code
798
+ after an `if` whose other branch exits (`if (!validateUser(input)) return;`), and the code after an assertion
799
+ call. Not a source: a guard your checked code declares (its written `x is T` is already a `claim:predicate`), a
800
+ validator, a guard declared by `@noego/trust`, and the built-in checks below.
801
+
802
+ It stays untrusted through `await`, `!`, parentheses, an assertion, `?:`, `??` / `||` / `&&`, and a `const` /
803
+ `let` with no written type. An untrusted value may only be:
804
+
805
+ - passed to a validator (a function marked [`//trust:validator_function`](#validators-trustvalidator_function));
806
+ - kept as `unknown`: stored, assigned, passed or returned where `unknown` is expected (`any` too; `type-claim`
807
+ reports that one);
808
+ - tested by a built-in check: `typeof`, `in`, `instanceof`, `Array.isArray`, `===` / `!==`, truthiness;
809
+ - thrown, discarded, or kept in a variable with no written type (it is still untrusted there).
810
+
811
+ Any other use is a finding that names the origin: passing or storing it where a type is expected, returning it
812
+ from a function that does not return `unknown`, reading a member, computing with it, iterating or spreading it.
813
+
814
+ ```ts
815
+ const row = fetchRow(); // untrusted (returned by "pg-lib.fetchRow"), nothing reported yet
816
+ save(row); // finding: passed where "Row" is expected
817
+ const kept: unknown = fetchRow(); // fine: kept as unknown
818
+ const parsed = parseRow(fetchRow()); // fine: parseRow is a validator
819
+ ipcMain.handle('save', (event, payload: Order) => payload.id); // finding: read through its member "id"
820
+ const port: unknown = process.env.PORT; // fine
821
+ if (typeof port === 'string') listen(Number(port)); // fine: the compiler narrowed `unknown`
822
+ ```
823
+
824
+ Members: who declares the member decides what reading it is.
825
+
826
+ - A member declared by an origin that is not type-trusted (`event.data`, `row.name` of the package's own
827
+ `Row`), or by nothing at all (an index signature: `process.env.PORT`), is a **read**: no finding, and the
828
+ member is the untrusted value, judged where it is used in turn.
829
+ - A member declared by checked code or by a type-trusted origin (`payload.id` of your own `Order`,
830
+ `text.length`) would come out looking trusted, so reading it from an untrusted value is the finding.
831
+ - A global or an imported constant (`process`, `JSON`, `location`) is a name, not a value that was handed
832
+ over: what is read from it is judged by the member's own declaration (`JSON.stringify` is fine with only
833
+ `js:JSON.stringify` type-trusted).
834
+
835
+ Narrowing happens on `unknown`. The compiler narrows a typed value against its declared type, and that type is
836
+ the unproven claim, so `typeof row.name === 'string'` is allowed but unlocks nothing; keep the value as
837
+ `unknown` and the compiler's own narrowing is the proof (a library's type guard is not: what it narrows is a
838
+ `guard` value). Nothing is reported for a value whose type claims
839
+ nothing: `unknown`, `any` (`type-claim` reports its uses), `void` / `undefined` / `null` / `never`, and functions
840
+ (a function is judged where it is called). That is why a `catch` variable never produces a finding here: it is
841
+ `unknown`, so the compiler already holds it. Uses inside a validator are not reported.
842
+
843
+ A caller-chosen generic return is reported twice on purpose: `type-claim` reports the call
844
+ (`claim:generic-return`), and `untrusted-value` reports each use of what it returned. A validator, or choosing
845
+ `unknown`, removes both. So does a `trust_type` entry **in your own config files** that covers the callee, at
846
+ member level or above: `"trust_type": ["@noego/ioc.Container.get"]` (or `["@noego/ioc"]`) says the container
847
+ returns whatever `T` the caller names, so `container.get<Foo>('x')` is neither a claim nor an untrusted value,
848
+ and a `distrust_type` entry that wins along the chain takes it back. Entries that come from the built-in presets
849
+ (`js`, `node`, `web`, `web_strict`, `svelte`) never unlock a caller-chosen return: a broad preset entry such as
850
+ `js:Array` must not silently bless `Array<User>(n)`; name the origin in your own config if you mean it. This
851
+ works for checked code too: a first-party generic is a claim unless your config names its `local:` origin
852
+ (`"trust_type": ["local:ui/actions/resolve_in_renderer_scope.ts#resolveSyncInScope"]`, the path relative to
853
+ the project root, i.e. the leaf config's directory).
854
+
855
+ Findings baseline per file + rule + origin, like every other rule, so `trust baseline --update` records today's
856
+ uses and only new ones fail. `trust explain <file>:<line>` prints the type-trust verdict of every call next to
857
+ its throw-trust verdict, and every untrusted value on the line with what became of it:
858
+
859
+ ```text
860
+ server/orders.ts:17 (zone: checked)
861
+
862
+ 17:11 fetchRow()
863
+ origin: pg-lib.fetchRow
864
+ verdict: UNTRUSTED (no trust entry matches)
865
+ hint: guard it, or trust "pg-lib.fetchRow" (or a prefix of it) in trust.config.json
866
+ types: UNTRUSTED (no trust_type entry matches)
867
+ validate what it returns, or add "pg-lib.fetchRow" (or a prefix of it) to "trust_type" in trust.config.json
868
+ declared: /repo/node_modules/pg-lib/index.d.ts:13
869
+
870
+ 17:11 fetchRow()
871
+ value: untrusted "Row", returned by "pg-lib.fetchRow" (rule untrusted-value)
872
+ use: Untrusted value returned by "pg-lib.fetchRow" is passed where "Row" is expected: its type "Row" is declared, not proven. …
873
+ ```
874
+
875
+ The `types:` line is one of: `trusted` (first-party code, `@noego/trust` itself, or a validator),
876
+ `type-trusted by "<entry>" in <config level>`, `UNTRUSTED (no trust_type entry matches)`,
877
+ `UNTRUSTED (type-distrusted by "<entry>" in <config level>)`, or `UNTRUSTED (the call picks its own return type …)`.
878
+
879
+ A call to a type guard or assertion function also gets `guard:` lines: what it narrows, the predicate, the
880
+ origin of its signature, and whether that origin is type-trusted:
881
+
882
+ ```text
883
+ 10:7 validateUser(input)
884
+ …
885
+ guard: narrows "input" (data is User), declared by "ajv.ValidateFunction"
886
+ UNTRUSTED (no trust_type entry matches): the narrowed value is untrusted (rule untrusted-value)
887
+ validate the value instead, or add "ajv.ValidateFunction" (or a prefix of it) to "trust_type" in trust.config.json
888
+ ```
889
+
890
+ #### Callbacks not written inline (`"untrustedCallbacks": "all"`)
891
+
892
+ With the default `"inline"`, a callback is linked to the origin that calls it only when it is written inline at
893
+ the call. A function written any other way adopts the library's declared type silently:
894
+ `function handle(data: Mine) { … }; ws.on('message', handle)` reports nothing. Set
895
+ `"rules": { "untrustedCallbacks": "all" }` to judge every function you hand to an origin that is not
896
+ type-trusted, at the hand-off:
897
+
898
+ - At every call / `new` into such an origin, each argument whose expected type has call signatures (a callback)
899
+ or methods (a handler object, a class instance) is resolved to the functions it hands over: a named function,
900
+ a `const` function, `this.method`, `fn.bind(...)` (bound arguments skipped), the methods and properties of an
901
+ object literal (or of a `const` holding one), and the methods and function fields of a class instance.
902
+ - A class that `implements` an interface such an origin declares is judged at its `implements` clause, each
903
+ implementing method against the interface member.
904
+ - Each parameter the origin fills whose type claims something (anything but `unknown` / `any`; an unconstrained
905
+ type parameter counts as `unknown`) is a finding at the hand-off, naming the origin:
906
+
907
+ ```text
908
+ "handle" receives data from "ws.WebSocket.on" but declares its parameter "data" as "Mine", which nothing
909
+ proves. Declare the parameter `unknown` and validate it, or, if "ws.WebSocket.on" declares true types, add it
910
+ to "trust_type" in trust.config.json.
911
+ ```
912
+
913
+ The function itself is not tainted: first-party code may call `handle` with a value it has checked, and those
914
+ calls are not reported. The way out is configuration only: a `trust_type` entry for the method that calls it
915
+ (`"ws.WebSocket.on"`, `"evil-lib.on"`) clears every hand-off to it (and the inline case too, when the callback's
916
+ signature is written in that method's declaration, as in `on(event, handler: (data: Payload) => void)`); for `implements`, the
917
+ entry is the interface member (`"evil-lib.Handler.onData"`) or the interface. An inline arrow or function
918
+ expression is unchanged: its parameters stay untrusted values judged where they are used, exactly as under
919
+ `"inline"`. Nothing is reported inside a validator, and a validator handed over is not questioned. `"inline"` and
920
+ `"off"` report none of these findings; turning `"all"` on adds only them, so run `trust baseline --update` after.
921
+
922
+ Not covered: values that reach a field or a collection through code that is not checked, and a function handed
923
+ over through a parameter or a mutable variable (`let`), whose value is not known where it is handed over.
924
+
925
+ ### `dropped-result`: every failure is passed up or handled
926
+
927
+ The trust rules turn every throw into a `Result`; `dropped-result` makes sure no `Result` that can still fail is
928
+ then lost. It is opt-in: `"rules": { "dropped-result": "on" }` in trust.config.json (`trust check`, `trust baseline`
929
+ and the ESLint rule `trust/dropped-result` read the same switch).
930
+
931
+ A value can fail when its type has an `Err` member (awaited, and one level into an array or tuple, so
932
+ `Promise.all([...])` counts). Each such value is followed through the function that holds it, path by path, and must
933
+ end in one of two ways:
934
+
935
+ - **passed up**: returned (`return r`, `if (!r.ok) return r;`, an arrow function's expression body), or flowing into
936
+ a call whose own value can fail (`Promise.all`, a wrapper returning it). On a path where a value is known to be an
937
+ `Err`, returning any value that can fail passes it up (`if (!r.ok) return Result.err({ kind: 'LoadFailed' })`), and
938
+ the first failure returned covers the values not checked yet on that path.
939
+ - **carried out**: the returned value takes the failure along, whatever its type: `return this.failed(r.error)`,
940
+ `return reply(r)`, `return { error: r.error }`, or a call's `Result` returned inside the response
941
+ (`return this.reply('status', await svc.status())`). This is how a controller hands its failures to the
942
+ framework. Reading only `r.ok` / `r.value` carries nothing, and neither does a call that returns nothing.
943
+ - **handled**: `Trust.decide` / `Trust.translate` (what they leave is a new value, followed the same way), a branch
944
+ that names the kind (`r.error.kind === 'NotFound'`, `case 'NotFound':`), or handed to a parameter whose declared
945
+ type is a `Result` (that function is checked in turn, its parameter followed like a variable).
946
+ In a `switch (r.error.kind)`, each `case` narrows to its kind and a `default` receives only the kinds no
947
+ `case` names; with every kind named, the `default` has nothing left, which is the exhaustive form
948
+ (see [The edge decides everything that is left](#the-edge-decides-everything-that-is-left)).
949
+
950
+ Everything else is reported with the kinds still possible there. The origin is the baseline key:
951
+
952
+ | Origin | What dropped the failure |
953
+ |---|---|
954
+ | `discarded` | a call's `Result` nobody keeps: an expression statement, `void`, `f().ok` |
955
+ | `argument` | a call's `Result` passed where no `Result` is expected (`console.log(f())`) |
956
+ | `stored` | a call's `Result` put where failures are not followed (an object property, a field) |
957
+ | `callback` | a function returning a `Result` handed to a callee that takes no `Result` back (`forEach`, an event listener) |
958
+ | `return` | a `return` that neither passes a variable up nor follows a check that handled it (`if (!r.ok) return null`) |
959
+ | `end` | a variable that can still fail when it goes out of scope: the end of its function or block (falling off the end of an `if` / `else if` chain that misses a kind), a `break` / `continue` |
960
+ | `overwritten` | a variable assigned again while it can still fail |
961
+
962
+ ```ts
963
+ const r = find(); // Result<number, { kind: 'NotFound' } | { kind: 'Locked' }>
964
+ if (r.ok) return Result.ok(r.value);
965
+ else if (r.error.kind === 'NotFound') return Result.ok(0);
966
+ // dropped-result (end): `r` can still fail with "Locked" when it goes out of scope here
967
+ ```
968
+
969
+ A kind that is not a string literal (`{ kind: string }`) can never be named away: such a value is passed up or
970
+ decided. Variables are followed in the function that declares them; a module-level variable is not followed, and a
971
+ closure reading a variable of an outer function does not handle it. Control flow is followed through if / else,
972
+ switch, loops (one pass), try / catch / finally, labels, break and continue; conditions narrow on `r.ok` (with `!`,
973
+ `&&`, `||`, `=== true` / `false`) and on `r.error.kind` compared with a string literal. `//trust:accept` does not
974
+ accept a dropped-result finding.
975
+
976
+ ### `redundant-guard`: a guard around code that cannot fail
977
+
978
+ The other half of the same contract: a guard (`Trust.try` / `Trust.tryAsync`, or a `try` whose `catch` returns
979
+ `Result.err`) turns a throw into a named failure, so around code that cannot throw it invents a failure path. Every
980
+ caller then holds a `Result` whose `Err` never happens, and a caller that forgets to unwrap it uses the `Result` as
981
+ the value. Opt-in: `"rules": { "redundant-guard": "on" }`.
982
+
983
+ The guarded code can fail when it holds, outside nested functions: a call or `new` whose origin is untrusted,
984
+ unresolved or in an ignored file; a call into first-party code not declared to return a `Result` (it may still
985
+ throw); a `throw`; a dynamic `import()`; an `await` (or `for await`) of something that is not a call. Calls into
986
+ trusted origins and to functions declared to return a `Result` cannot fail. A guard around only those is reported at
987
+ the guard (origin `redundant`):
988
+
989
+ ```ts
990
+ // trust.config.json trusts @noego/ioc: resolution failures are programmer errors at boot
991
+ async instance<T>(token: new () => T) {
992
+ return Trust.tryAsync(() => this.scope.instance(token), (cause) => ({ kind: 'resolution_failed', cause }));
993
+ // redundant-guard: `Trust.tryAsync` guards nothing that can fail: every call inside is trusted ("@noego/ioc…")
994
+ }
995
+ ```
996
+
997
+ Fix it by calling directly and returning the value. If the call really can fail, the trust entry is wrong: remove the
998
+ origin from `trust`, and the guard becomes required again.
999
+
1000
+ ### `trust refactor`: the order to refactor in
1001
+
1002
+ ```sh
1003
+ trust refactor [paths...] [--json] [--value-only] [--max-group <n>] [--baseline <path>] [--config <path>] [--tsconfig <path>] [--root <dir>]
1004
+ ```
1005
+
1006
+ A file's inferred failure and return types change when the files it imports change, so fixing findings top-down
1007
+ means doing work twice. `trust refactor` prints the order that avoids it. It builds the static import graph of
1008
+ the files `trust baseline` would check (same file walk, same programs and `tsconfig` mapping, `ignore` zone
1009
+ skipped; the current directory when no path is given) and prints a plan:
1010
+
1011
+ ```json
1012
+ { "waves": [["a.ts", "b.ts", ["c.ts", "d.ts"]], ["e.ts"]] }
1013
+ ```
1014
+
1015
+ - A **wave** is a list of work items that can be done in parallel. A wave starts when the wave before it is
1016
+ done: everything a file imports is in an earlier wave, so the first wave is the leaves.
1017
+ - A **string** is one file. An **array** is a circular-import group: files that import each other, directly or
1018
+ through other files, and so must be refactored together.
1019
+ - Only files with findings are in the plan. A file with no findings is left out, but the order it carries is
1020
+ kept: if `top.ts` imports `clean.ts` and `clean.ts` imports `leaf.ts`, `top.ts` still comes after `leaf.ts`.
1021
+ In a circular group only the files with findings are listed; a group with one such file is a plain string.
1022
+
1023
+ The findings come from `trust-baseline.json` in the project root (or `--baseline <path>`, which must exist): a
1024
+ file is work when the baseline has a count above zero for it. With no baseline file the command runs a fresh
1025
+ check (the rules `trust baseline` counts) and uses the files that have findings. The last line of the text
1026
+ output says which one was used.
1027
+
1028
+ How imports become edges:
1029
+
1030
+ - A named or default import, and a named re-export, points at the file that declares the name. An import through
1031
+ a barrel (`export { a } from './a'`) depends on `a.ts`, not on the barrel, so barrels do not create cycles.
1032
+ - `import * as`, `export *`, `import x = require(...)`, `import './x'` and `import('./x')` point at the module file.
1033
+ - Type-only imports count (inferred types flow through them). `--value-only` leaves out the ones written as
1034
+ type-only: `import type`, `export type`, `{ type X }`, and `import('./x').T` in a type.
1035
+ - Only the files of the run are in the graph: an import of a file outside the paths, in the `ignore` zone, or in
1036
+ `node_modules` is not an edge.
1037
+
1038
+ What the graph cannot see is reported, not guessed:
1039
+
1040
+ - `import(expression)` with a computed specifier is listed under `warnings` (file, line, column, and the
1041
+ expression's text). Order the files it loads by hand.
1042
+ - A file that no program can load, or that does not parse, stops the run (exit 2), as in `trust baseline`.
1043
+
1044
+ `--json` prints one document: `waves` as above, plus `cycles` (every circular group, largest first, with `size`,
1045
+ all its `files`, the `tasks` among them, `tooLarge` and `closingEdges`), `warnings`, and a `summary` (files and
1046
+ import edges in the graph, files with findings, work items, ignored files, where the findings came from).
1047
+ The text output prints the same plan as `Wave 1 of N`, `Wave 2 of N`, …, then the circular groups, the computed
1048
+ imports and a one-line summary. Exit code 0 means a plan was printed; 2 means the command could not run
1049
+ (TypeScript not found, unreadable tsconfig or baseline, a missing path, or a file that does not load).
1050
+
1051
+ #### Circular groups: what closes them
1052
+
1053
+ Every circular group lists its **closing edges**: a small set of imports without which the group has no cycle.
1054
+
1055
+ ```json
1056
+ { "from": "view.ts", "to": "model.ts", "names": ["LIMIT", "Model"] }
1057
+ ```
1058
+
1059
+ reads "`view.ts` imports `LIMIT` and `Model` from `model.ts`" (`*` is the module as a whole). Removing these
1060
+ imports is optional structural cleanup: it ends the circle for good. A common case is a types file that imports
1061
+ an implementation. The set is chosen to be cheap to cut (an import of names that cannot change, such as an
1062
+ interface, costs less than an import of a function); it is small, but not always the smallest possible.
1063
+
1064
+ #### Circular groups that are too large
1065
+
1066
+ A circular group with more than 8 files (`--max-group <n>` changes the limit) is `tooLarge`: too large for one
1067
+ unit of work. The command shrinks it in three steps. Groups at or under the limit are left as they are, and a
1068
+ unit above the limit is never emitted without saying so.
1069
+
1070
+ **1. Imports that cannot carry a change are dropped.** An import orders two files only when what it imports can
1071
+ change because of the refactor:
1072
+
1073
+ | Imported | Can it change? |
1074
+ | --- | --- |
1075
+ | A function, method, accessor or constructor with a body | Yes. Its inferred types follow what it calls. A written return type that is not a `Result` is rewritten when the function fails |
1076
+ | A function whose written return type is a `Result` (or a promise of one) | No. It is a frozen contract |
1077
+ | A variable or property with an inferred type | Yes, unless its value is a literal (`10`, `'x'`, `[1, 2] as const`, an object of literals) |
1078
+ | A class | Yes, when a member or its base class can |
1079
+ | An interface, a type alias, a written type annotation, a signature without a body | Only when it mentions something that can: `typeof load`, a class |
1080
+ | An enum, anything in a `.d.ts` file, an import that binds no name (`import './x'`) | No |
1081
+ | A whole module (`import * as`, `export *`, `import('./x')`) | Yes, when one of its exports can |
1082
+ | Anything else | Yes. The import is kept when in doubt |
1083
+
1084
+ The group is planned again without the imports that cannot carry a change. `waves` then holds what is left of it:
1085
+ smaller groups and single files, each in its own place. The group's entry in `cycles` gets
1086
+ `split: { droppedEdges, keptEdges, groups }`, where `groups` are the circular groups still inside it (empty when
1087
+ it fell apart). Only imports inside a too-large group are dropped; every other import orders its files as before.
1088
+ This step looks at what is imported, not at how the import is written: `import { Model }` of an interface is
1089
+ dropped, `import type { Store }` of a class with methods is kept.
1090
+
1091
+ **2. A group that is still too large gets an internal order.** It stays one work item (an array in `waves`), and
1092
+ its entry under `split.groups` has `tooLarge: true` and an `order`: the declarations with findings, in waves,
1093
+ callees first.
1094
+
1095
+ ```json
1096
+ { "order": [["c.ts#load"], ["d.ts#save"], ["c.ts#report"]], "recursion": [] }
1097
+ ```
1098
+
1099
+ Files that import each other in a circle usually do not call each other in a circle, so the order comes from the
1100
+ calls between declarations (each call is resolved the way `trust explain` resolves it). A declaration is named
1101
+ `file#name`: `c.ts#load`, `c.ts#Store.load` for a class member, `c.ts#Tools.run` inside a namespace,
1102
+ `c.ts#default` for an unnamed default export, and `c.ts#(top level)` for statements outside any declaration.
1103
+ Code nested in a declaration (a callback, an inner function) belongs to it. A declaration is work when a fresh
1104
+ check finds a finding in it and its file has findings; the other declarations only carry the order. A call
1105
+ counts when its callee can change by the table above, so a call through an interface member or to a function with
1106
+ a frozen contract orders nothing. Only calls are followed: a function passed as a value is not.
1107
+
1108
+ **3. Mutual recursion is reported.** Declarations that call each other in a circle have no order. They are one
1109
+ array in `order`, and `recursion` lists each such circle with its `declarations`, the `files` they are in, the
1110
+ calls that close it (`closingEdges`, with `callSites`), and `freeze`. There are two ways out:
1111
+
1112
+ - **Freeze a contract.** Write the return type of one callee as a `Result` by hand. Changes stop travelling
1113
+ through it, and the rest gets an order. `freeze` names the callee of a closing call with the fewest call sites
1114
+ in the group's files.
1115
+ - **Iterate to a fixed point.** Refactor the declarations of the circle in passes until their inferred failure
1116
+ types stop changing. Inferred failure sets only grow, so this ends.