@frankmeza/affirm 0.0.0-stage → 0.0.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 (51) hide show
  1. package/AGENTS.md +130 -0
  2. package/LICENSE +21 -0
  3. package/README.md +116 -2
  4. package/dist/affirm.d.ts +79 -0
  5. package/dist/checks/arrays.d.ts +10 -0
  6. package/dist/checks/composition.d.ts +10 -0
  7. package/dist/checks/equality.d.ts +7 -0
  8. package/dist/checks/nullish.d.ts +9 -0
  9. package/dist/checks/numbers.d.ts +11 -0
  10. package/dist/checks/objects.d.ts +9 -0
  11. package/dist/checks/runtime-type.d.ts +14 -0
  12. package/dist/checks/size.d.ts +8 -0
  13. package/dist/checks/strings.d.ts +6 -0
  14. package/dist/core/check-def.d.ts +93 -0
  15. package/dist/core/describe.d.ts +11 -0
  16. package/dist/core/errors.d.ts +18 -0
  17. package/dist/core/evaluate.d.ts +8 -0
  18. package/dist/core/registry.d.ts +18 -0
  19. package/dist/core/report.d.ts +22 -0
  20. package/dist/core/util/deep-equal.d.ts +12 -0
  21. package/dist/core/util/kind.d.ts +22 -0
  22. package/dist/core/util/levenshtein.d.ts +3 -0
  23. package/dist/core/util/same-value-zero.d.ts +5 -0
  24. package/dist/core/util/standard-schema.d.ts +62 -0
  25. package/dist/core/validate-params.d.ts +8 -0
  26. package/dist/eslint/check-keys.d.ts +7 -0
  27. package/dist/eslint/const-params.d.ts +2 -0
  28. package/dist/eslint/guard-naming.d.ts +2 -0
  29. package/dist/eslint/index.d.ts +29 -0
  30. package/dist/eslint/no-negated-affirm.d.ts +2 -0
  31. package/dist/eslint/shared.d.ts +65 -0
  32. package/dist/eslint.js +734 -0
  33. package/dist/eslint.js.map +1 -0
  34. package/dist/index.d.ts +5 -0
  35. package/dist/index.js +967 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/types/affirmed.d.ts +55 -0
  38. package/dist/types/arrays.d.ts +64 -0
  39. package/dist/types/composition.d.ts +53 -0
  40. package/dist/types/contradictions.d.ts +90 -0
  41. package/dist/types/equality.d.ts +65 -0
  42. package/dist/types/narrowing.d.ts +66 -0
  43. package/dist/types/nullish.d.ts +80 -0
  44. package/dist/types/numbers.d.ts +94 -0
  45. package/dist/types/objects.d.ts +99 -0
  46. package/dist/types/params.d.ts +14 -0
  47. package/dist/types/runtime-type.d.ts +129 -0
  48. package/dist/types/size.d.ts +76 -0
  49. package/dist/types/strings.d.ts +49 -0
  50. package/docs/client-usage.md +850 -0
  51. package/package.json +58 -4
package/AGENTS.md ADDED
@@ -0,0 +1,130 @@
1
+ # affirm: usage guide for coding agents
2
+
3
+ `affirm(value, params)` replaces compound data checks with one object of named checks. It returns a boolean and narrows `value`'s type.
4
+
5
+ ```ts
6
+ // instead of
7
+ if (order && typeof order === 'object' && 'total' in order && typeof order.total === 'number' && order.total > 0) { … }
8
+
9
+ // write
10
+ if (affirm(order, { hasKey: 'total', shape: { total: { isType: 'number', isPositive: true } } })) {
11
+ order.total // number
12
+ }
13
+ ```
14
+
15
+ Every key has hover docs with its exact pass condition and an example. When unsure what a key does, read its JSDoc in `AffirmParams`.
16
+
17
+ For more detail, including scenario recipes, report formats, a narrowing table and pitfalls that compile but are wrong, see [`docs/client-usage.md`](docs/client-usage.md).
18
+
19
+ ## API
20
+
21
+ ```ts
22
+ import { affirm, AffirmError } from '@frankmeza/affirm'
23
+
24
+ affirm(value, params) // boolean; narrows `value` in the if-branch
25
+ affirm.explain(value, params) // { ok, failures }: every failure, with paths
26
+ affirm.assert(value, params, message?) // throws AffirmError on failure; narrows afterwards
27
+ ```
28
+
29
+ Requires TypeScript 5.9 or later. On older versions, narrowing silently breaks: every `else` branch becomes `never`.
30
+
31
+ Lint client code with the bundled plugin. It enforces Rule 10, which TypeScript can't check:
32
+
33
+ ```js
34
+ // eslint.config.js
35
+ import affirm from '@frankmeza/affirm/eslint'
36
+ export default [affirm.configs.recommended, { settings: { affirm: { guards: '^isValid' } } }]
37
+ ```
38
+
39
+ `guards` is a naming contract: functions that just return `affirm(…)` must be named by it, and nothing else may be. That lets the rule catch `!isValidOrder(x)` even when the guard is imported. Functions imported from packages never count. If you import your own code through a path alias, add it: `guardModules: ['@/']`.
40
+
41
+ ## Rules
42
+
43
+ 1. **Value first, params second.** `affirm(value, { … })`, never `affirm({ value, … })`.
44
+ 2. **Keys combine with AND.** For OR, use `anyOf: [{ … }, { … }]`.
45
+ 3. **An omitted or `undefined` key is skipped.** You can build params conditionally: `{ hasMinLength: strict ? 8 : undefined }`.
46
+ 4. **Boolean keys: `true` asserts, `false` asserts the negation.** `isNull: false` means "is not null".
47
+ 5. **No coercion.** `isGreaterThan: 5` fails on `'10'`; `hasMinLength: 3` fails on a number.
48
+ 6. **The wrong kind of value fails both polarities.** `isPositive: false` means "a number that is not positive", so it fails on `'x'`. The same goes for `isInteger`, `isBlank`, `isEmpty`, `isValidDate`, ….
49
+ 7. **Data failures return `false`; mistakes throw `TypeError`.** These throw: unknown keys (with a "did you mean" hint), empty params `{}`, wrong param types (`matches: 'abc'`), and async schemas. Don't wrap `affirm` in try/catch to handle bad data.
50
+ 8. **Equality is `===`.** `isOneOf` and `contains*` use SameValueZero (`NaN` matches `NaN`). Use `isDeepEqual` for structure.
51
+ 9. **Own keys only.** `hasKey`, `hasPath`, `shape` and friends use `Object.hasOwn`. For prototype getters or class instances, use `satisfies`.
52
+ 10. **Never negate `affirm()`.** `!affirm(…)`, `affirm(…) === false`, a negated variable holding its result (`!ok`), and a negated same-file wrapper (`!isOrder(x)`) are lint errors (`affirm/no-negated-affirm`). With `settings.affirm.guards`, negated guards imported from other files are lint errors too. Name every guard built on `affirm` by that pattern. `affirm` is an AND of narrow checks, so its negation means "something failed, for some reason", which is too broad to build on. Instead: `affirm.assert` to stop on bad data, `affirm.explain` (`if (!report.ok)`) to handle failures by reason, or a positive check for the state you mean (`if (affirm(x, { isNull: true })) return`). The `not:` key is fine: it negates one named sub-check.
53
+
54
+ ## Keys at a glance
55
+
56
+ | Group | Keys |
57
+ | --- | --- |
58
+ | Equality | `is`, `isNot`, `isOneOf`, `isNotOneOf`, `isDeepEqual` |
59
+ | Nullish | `isNull`, `isUndefined`, `isNullish`, `isDefined` (≠ undefined), `isPresent` (≠ null and ≠ undefined), `isTruthy`, `isFalsy` |
60
+ | Runtime type | `isType` (`'string'`, `'number'`, `'boolean'`, `'bigint'`, `'symbol'`, `'function'`, `'object'`, a type guard, or a sync Standard Schema), `isArray`, `isPlainObject`, `isFunction`, `isInstanceOf`, `isValidDate`, `isInteger`, `isFiniteNumber`, `isNaN` |
61
+ | Size (strings, arrays, Maps, Sets) | `isEmpty`, `isNotEmpty` (also plain objects), `isBlank`, `hasLength`, `hasMinLength`, `hasMaxLength` |
62
+ | Numbers | `isGreaterThan`, `isAtLeast` (≥), `isLessThan`, `isAtMost` (≤), `isBetween: [min, max]` (**inclusive**), `isPositive`, `isNegative`, `isMultipleOf` |
63
+ | Strings | `startsWith`, `endsWith`, `includes` (strings only), `matches: RegExp` |
64
+ | Objects | `shape: { field: params }`, `hasKey`, `hasKeys`, `hasAnyKey`, `hasOnlyKeys`, `hasPath: 'a.b.0.c'` |
65
+ | Arrays | `contains` (arrays only), `containsAll`, `containsAny`, `everyItem: params`, `someItem: params` |
66
+ | Composition | `not: params`, `anyOf: [params, …]`, `satisfies: (v) => boolean` (runs last) |
67
+
68
+ Naming: `is*` describes state, `has*` describes possession, and `contains*` / `matches` / `startsWith` / … describe a search.
69
+
70
+ ## Recipes
71
+
72
+ ```ts
73
+ // Present, non-empty string
74
+ affirm(name, { isType: 'string', isBlank: false })
75
+
76
+ // Null or empty (isEmpty fails on null by itself)
77
+ affirm(input, { anyOf: [{ isNullish: true }, { isEmpty: true }] })
78
+
79
+ // Nullable field inside an object
80
+ affirm(user, { shape: { middleName: { anyOf: [{ isNull: true }, { isType: 'string' }] } } })
81
+
82
+ // Optional field: missing fields are checked as undefined
83
+ affirm(user, { shape: { nickname: { anyOf: [{ isUndefined: true }, { isType: 'string' }] } } })
84
+
85
+ // Enum
86
+ affirm(status, { isOneOf: ['draft', 'published', 'archived'] })
87
+
88
+ // Array of objects
89
+ affirm(order.items, {
90
+ isNotEmpty: true,
91
+ everyItem: { shape: { sku: { isBlank: false }, qty: { isInteger: true, isAtLeast: 1 } } },
92
+ })
93
+
94
+ // Exact keys only
95
+ affirm(query, { isPlainObject: true, hasOnlyKeys: ['page', 'limit'] })
96
+
97
+ // Cross-field rule: `satisfies` receives `unknown`, so guard first
98
+ affirm(range, { satisfies: (r) => isRange(r) && r.min <= r.max })
99
+
100
+ // An existing Zod / Valibot / ArkType schema (sync only; validates, never transforms)
101
+ affirm(body, { isType: OrderSchema })
102
+
103
+ // Config at startup: throw with a clear message
104
+ affirm.assert(env.PORT, { isType: 'string', matches: /^\d+$/ }, 'PORT must be numeric')
105
+
106
+ // Explain why a request body failed (safe to log: no raw values)
107
+ const report = affirm.explain(body, { shape: { email: { matches: /@/ } } })
108
+ if (!report.ok) return badRequest(report.failures.map((f) => f.reason))
109
+ // e.g. "items[2].id: expected length >= 3, received string(len 2)"
110
+ ```
111
+
112
+ ## Type narrowing
113
+
114
+ - **Exact checks** narrow both branches. These are `isNull`, `isUndefined`, `isNullish`, `isDefined`, `isPresent`, `isType` with a primitive tag or guard, `isArray: true`, `isFunction: true`, `is`/`isOneOf` with literals, and `anyOf` of exact branches. Example: with `x: string | null`, after `if (affirm(x, { isNull: true })) return`, `x` is `string`.
115
+ - **Refined checks** (all others) narrow only the `if` branch. The type gets a phantom `& Refined` marker, which you can ignore: a `string & Refined` works anywhere a `string` does. The `else` branch keeps the full type, because a value can fail for other reasons.
116
+ - **No narrowing at all** happens for refined checks whose result could be `null` or `undefined` (e.g. `isFalsy` on `string | null`). TypeScript can't express that soundly, so `affirm` returns a plain boolean. If you need narrowing, split the check: `affirm(x, { isPresent: true }) && affirm(x, { … })`.
117
+ - **Contradictions are compile errors**, e.g. "`isNull: true` contradicts `isPresent: true`" or "`hasMinLength: 10` is greater than `hasMaxLength: 9`". So are unknown keys at any depth.
118
+ - Name a narrowed type with `Affirmed<Input, Params>`.
119
+
120
+ ## Don't
121
+
122
+ - **Don't store params in a variable without `as const`.** `const p = { isOneOf: ['a', 'b'] }` is widened to `string[]` before `affirm` sees it, so it narrows to `string`, not `'a' | 'b'`. Write `const p = { … } as const` (or `as const satisfies AffirmParams`), never `const p: AffirmParams = …`. `affirm/const-params` flags this, including params exported from other files (recognised by their keys), and `eslint --fix` adds `as const`. Write lists used in params (`isOneOf: ROLES`) `as const` too; with type-aware linting (`projectService`), imported lists that aren't are reported at the use.
123
+ - **Don't negate `affirm()`** (Rule 10). No `if (!affirm(…)) return` guard clauses: use `affirm.assert`, `explain`, or put the main path in the positive branch.
124
+ - **Don't use `affirm` to parse or transform** (coercion, defaults, trimming). Use a schema library, then `affirm` its result or pass the schema as `isType`.
125
+ - **Don't write `isType: 'null'` or `isType: 'undefined'`** (they throw). Use `isNull` / `isUndefined`.
126
+ - **Don't pass a class to `isType`.** Use `isInstanceOf`.
127
+ - **Don't use `includes` on arrays or `contains` on strings.** They fail. `includes` is for substrings, `contains` is for array items.
128
+ - **Don't pass a string to `matches`.** It needs a `RegExp`; use `includes` for plain text.
129
+ - **Don't use `{}` as params**, or `shape: {}` / `anyOf: []`. They throw (they would always pass).
130
+ - **Don't put secrets in params expecting them to stay out of logs.** Reports never include checked values, but short param literals do appear in `expected` (e.g. `=== "admin"`).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Frank Meza
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ # @frankmeza/affirm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Runtime checks that read like a spec. `affirm(value, params)` replaces a compound `if` with one object of named checks. It returns a boolean and narrows `value`'s type.
4
+
5
+ ```ts
6
+ // before: what is this actually checking?
7
+ if (order && typeof order === 'object' && 'total' in order && typeof order.total === 'number' && order.total > 0) { … }
8
+
9
+ // after
10
+ if (affirm(order, { shape: { total: { isType: 'number', isPositive: true } } })) {
11
+ order.total // number
12
+ }
13
+ ```
14
+
15
+ ## Why
16
+
17
+ More and more code is written by coding agents and read by people in pull requests. Hand-rolled checks are where intent gets lost. `x && x.length > 0 && !/^\s*$/.test(x)` takes a reviewer a moment to decode, and a subtle mistake in it (`>=` instead of `>`, a missing `typeof`) is easy to miss.
18
+
19
+ With `affirm`, every condition is a named key (`isBlank: false`, `hasMinLength: 3`, `isBetween: [1, 10]`), so a reviewer can read what the code requires and judge whether that's the right requirement. Behind that:
20
+
21
+ - **TypeScript narrowing.** Exact checks narrow both branches; the others narrow the `if` branch. Contradictory params, such as `isNull: true` with `isPresent: true`, are compile errors.
22
+ - **Failure reports.** `affirm.explain` lists every failure with its path (`items[2].id: expected length >= 3, received string(len 2)`). Reports never include the values being checked.
23
+ - **Built for agents.** The package ships an [`AGENTS.md`](AGENTS.md) usage guide for coding agents, and every key has hover docs with its exact pass condition.
24
+ - **An ESLint plugin** that catches the mistakes TypeScript can't, such as negated checks and params that lose their literal types.
25
+ - **No runtime dependencies.** Works with Zod, Valibot and ArkType schemas through [Standard Schema](https://standardschema.dev).
26
+
27
+ `affirm` checks values. It doesn't parse or transform them: no coercion, defaults or trimming. Use a schema library for that, and pass the schema to `affirm` as `isType`.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ npm install @frankmeza/affirm
33
+ ```
34
+
35
+ Requires **TypeScript 5.9 or later** with `strictNullChecks` (or `strict`). On older versions narrowing silently breaks: every `else` branch becomes `never`.
36
+
37
+ ## Usage
38
+
39
+ ```ts
40
+ import { affirm, AffirmError } from '@frankmeza/affirm'
41
+
42
+ affirm(value, params) // boolean; narrows `value` in the if-branch
43
+ affirm.explain(value, params) // { ok, failures }: every failure, with paths
44
+ affirm.assert(value, params, message?) // throws AffirmError on failure; narrows afterwards
45
+ ```
46
+
47
+ ```ts
48
+ // Present, non-empty string
49
+ affirm(name, { isType: 'string', isBlank: false })
50
+
51
+ // Enum
52
+ affirm(status, { isOneOf: ['draft', 'published', 'archived'] })
53
+
54
+ // Array of objects
55
+ affirm(order.items, {
56
+ isNotEmpty: true,
57
+ everyItem: { shape: { sku: { isBlank: false }, qty: { isInteger: true, isAtLeast: 1 } } },
58
+ })
59
+
60
+ // OR
61
+ affirm(input, { anyOf: [{ isNullish: true }, { isEmpty: true }] })
62
+
63
+ // An existing schema
64
+ affirm(body, { isType: OrderSchema })
65
+
66
+ // Config at startup: throw with a clear message
67
+ affirm.assert(env.PORT, { isType: 'string', matches: /^\d+$/ }, 'PORT must be numeric')
68
+
69
+ // Explain why a request body failed
70
+ const report = affirm.explain(body, { shape: { email: { matches: /@/ } } })
71
+ if (!report.ok) return badRequest(report.failures.map((f) => f.reason))
72
+ ```
73
+
74
+ Keys combine with AND, an omitted or `undefined` key is skipped, and there's no coercion: `isGreaterThan: 5` fails on `'10'`. Mistakes in the params themselves, such as an unknown key or an empty `{}`, throw a `TypeError` with a "did you mean" hint, so they can't pass silently.
75
+
76
+ | Group | Keys |
77
+ | --- | --- |
78
+ | Equality | `is`, `isNot`, `isOneOf`, `isNotOneOf`, `isDeepEqual` |
79
+ | Nullish | `isNull`, `isUndefined`, `isNullish`, `isDefined`, `isPresent`, `isTruthy`, `isFalsy` |
80
+ | Runtime type | `isType`, `isArray`, `isPlainObject`, `isFunction`, `isInstanceOf`, `isValidDate`, `isInteger`, `isFiniteNumber`, `isNaN` |
81
+ | Size | `isEmpty`, `isNotEmpty`, `isBlank`, `hasLength`, `hasMinLength`, `hasMaxLength` |
82
+ | Numbers | `isGreaterThan`, `isAtLeast`, `isLessThan`, `isAtMost`, `isBetween`, `isPositive`, `isNegative`, `isMultipleOf` |
83
+ | Strings | `startsWith`, `endsWith`, `includes`, `matches` |
84
+ | Objects | `shape`, `hasKey`, `hasKeys`, `hasAnyKey`, `hasOnlyKeys`, `hasPath` |
85
+ | Arrays | `contains`, `containsAll`, `containsAny`, `everyItem`, `someItem` |
86
+ | Composition | `not`, `anyOf`, `satisfies` |
87
+
88
+ ## ESLint plugin
89
+
90
+ ```js
91
+ // eslint.config.js
92
+ import affirm from '@frankmeza/affirm/eslint'
93
+
94
+ export default [
95
+ affirm.configs.recommended,
96
+ { settings: { affirm: { guards: '^isValid' } } },
97
+ ]
98
+ ```
99
+
100
+ | Rule | Catches |
101
+ | --- | --- |
102
+ | `affirm/no-negated-affirm` | `!affirm(…)` and negated guards. `affirm` is an AND of narrow checks, so its negation only means "something failed", which is too broad to act on. Use `affirm.assert`, `affirm.explain`, or a positive check instead. |
103
+ | `affirm/guard-naming` | Guards built on `affirm` that don't follow the `guards` naming pattern, which is how negated guards are caught across files. |
104
+ | `affirm/const-params` | Params stored in a variable without `as const`, which lose their literal types before `affirm` sees them. Autofixable. |
105
+
106
+ Requires ESLint 9 or 10 with a flat config. `eslint` is an optional peer dependency.
107
+
108
+ ## Docs
109
+
110
+ - [`AGENTS.md`](AGENTS.md): the short guide for coding agents. Point your agent at it, for example from your own `AGENTS.md` or `CLAUDE.md`.
111
+ - [`docs/client-usage.md`](docs/client-usage.md): the full guide, with recipes, the report format, a narrowing table, pitfalls that compile but are wrong, and a checklist for reviewing generated code.
112
+
113
+ Both files ship in the package, so they're available under `node_modules/@frankmeza/affirm/`.
114
+
115
+ ## License
116
+
117
+ [MIT](LICENSE)
@@ -0,0 +1,79 @@
1
+ import type { AffirmReport } from './core/report';
2
+ import type { Affirmed, CanNarrow } from './types/affirmed';
3
+ import type { ParamsCheck } from './types/contradictions';
4
+ import type { AffirmParams } from './types/params';
5
+ /** Makes the narrowing overload inapplicable (so the boolean one is picked) when narrowing is unsound. */
6
+ type IfNarrowable<V, P> = CanNarrow<V, P> extends true ? unknown : never;
7
+ /**
8
+ * Design §6.1. `const P` keeps literal params (`is: 'admin'` narrows to `'admin'`).
9
+ * Declared as an explicit interface so `affirm.assert` can carry an `asserts` signature.
10
+ * Each narrowing signature has a non-narrowing twin for params where narrowing would be unsound
11
+ * (see `CanNarrow`).
12
+ */
13
+ export interface Affirm {
14
+ /**
15
+ * Checks `value` against named checks and returns `true` when all of them pass (keys combine
16
+ * with AND; use `anyOf` for OR). Narrows `value` in the `if` branch.
17
+ *
18
+ * Data failures return `false`; programmer errors (unknown key, empty params, wrong param type,
19
+ * async schema) throw `TypeError`. Use `affirm.explain` to see why a value failed.
20
+ *
21
+ * Never negate the result (`!affirm(…)`, `affirm(…) === false`): it means "some check failed, for
22
+ * some reason", which is too broad to rely on. Use `affirm.assert`, `affirm.explain`, or a positive
23
+ * check for the state you mean. Enforced by the `affirm/no-negated-affirm` lint rule.
24
+ *
25
+ * @example
26
+ * if (affirm(order, { isPresent: true, shape: { total: { isType: 'number', isPositive: true } } })) {
27
+ * order.total // number
28
+ * }
29
+ */
30
+ <V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P> & IfNarrowable<V, P>): value is Affirmed<V, P>;
31
+ /**
32
+ * Checks `value` against named checks and returns `true` when all of them pass.
33
+ * (This signature is used when narrowing would be unsound, e.g. `isFalsy` on `string | null`.)
34
+ *
35
+ * @example
36
+ * if (affirm(name, { isFalsy: true })) return 'anonymous'
37
+ */
38
+ <V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P>): boolean;
39
+ /**
40
+ * Evaluates every check and reports all failures, with paths like `items[2].id`.
41
+ * Never throws on data failures. Reports describe values by type only (`string(len 2)`),
42
+ * never by content, so they are safe to log.
43
+ *
44
+ * @example
45
+ * const report = affirm.explain(body, { shape: { email: { matches: /@/ } } })
46
+ * if (!report.ok) log.warn(report.failures.map((f) => f.reason))
47
+ */
48
+ explain<const P extends AffirmParams>(value: unknown, params: P & ParamsCheck<P>): AffirmReport;
49
+ /**
50
+ * Throws `AffirmError` (with the full report) unless every check passes; afterwards `value`
51
+ * is narrowed for the rest of the scope.
52
+ *
53
+ * @example
54
+ * affirm.assert(config.port, { isInteger: true, isBetween: [1, 65535] }, 'invalid PORT')
55
+ * server.listen(config.port) // number
56
+ */
57
+ assert<V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P> & IfNarrowable<V, P>, message?: string): asserts value is Affirmed<V, P>;
58
+ /**
59
+ * Throws `AffirmError` (with the full report) unless every check passes.
60
+ * (This signature is used when narrowing would be unsound.)
61
+ *
62
+ * @example
63
+ * affirm.assert(input, { isFalsy: true }, 'expected no input')
64
+ */
65
+ assert<V, const P extends AffirmParams>(value: V, params: P & ParamsCheck<P>, message?: string): void;
66
+ }
67
+ /**
68
+ * Replaces compound data checks with one readable object of named checks.
69
+ * See `AffirmParams` for every key, and `AGENTS.md` for the usage guide.
70
+ *
71
+ * @example
72
+ * import { affirm } from '@frankmeza/affirm'
73
+ *
74
+ * if (affirm(user, { isPresent: true, hasKey: 'email' })) { … }
75
+ * affirm.explain(user, { shape: { email: { matches: /@/ } } }) // { ok, failures }
76
+ * affirm.assert(user, { isPresent: true }) // throws AffirmError, then narrows
77
+ */
78
+ export declare const affirm: Affirm;
79
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { AffirmParams } from '../types/params';
2
+ export declare const arrayChecks: {
3
+ contains: import("../core/check-def").CheckDef<unknown>;
4
+ containsAll: import("../core/check-def").CheckDef<readonly unknown[]>;
5
+ containsAny: import("../core/check-def").CheckDef<readonly unknown[]>;
6
+ /** Failures carry the item path: `items[2].id`. Vacuously true on `[]`. */
7
+ everyItem: import("../core/check-def").CheckDef<AffirmParams>;
8
+ /** One failure when no item passes (per-item failures would just be noise). False on `[]`. */
9
+ someItem: import("../core/check-def").CheckDef<AffirmParams>;
10
+ };
@@ -0,0 +1,10 @@
1
+ import type { AffirmParams } from '../types/params';
2
+ export declare const compositionChecks: {
3
+ not: import("../core/check-def").CheckDef<AffirmParams>;
4
+ /**
5
+ * Passes when any branch passes. The failure lists every branch's failures in `branches`
6
+ * (all of them under `explain()`, the first per branch under `affirm()`).
7
+ */
8
+ anyOf: import("../core/check-def").CheckDef<readonly AffirmParams[]>;
9
+ satisfies: import("../core/check-def").CheckDef<(value: unknown) => boolean>;
10
+ };
@@ -0,0 +1,7 @@
1
+ export declare const equalityChecks: {
2
+ is: import("../core/check-def").CheckDef<unknown>;
3
+ isNot: import("../core/check-def").CheckDef<unknown>;
4
+ isOneOf: import("../core/check-def").CheckDef<readonly unknown[]>;
5
+ isNotOneOf: import("../core/check-def").CheckDef<readonly unknown[]>;
6
+ isDeepEqual: import("../core/check-def").CheckDef<unknown>;
7
+ };
@@ -0,0 +1,9 @@
1
+ export declare const nullishChecks: {
2
+ isNull: import("../core/check-def").CheckDef<boolean>;
3
+ isUndefined: import("../core/check-def").CheckDef<boolean>;
4
+ isNullish: import("../core/check-def").CheckDef<boolean>;
5
+ isDefined: import("../core/check-def").CheckDef<boolean>;
6
+ isPresent: import("../core/check-def").CheckDef<boolean>;
7
+ isTruthy: import("../core/check-def").CheckDef<boolean>;
8
+ isFalsy: import("../core/check-def").CheckDef<boolean>;
9
+ };
@@ -0,0 +1,11 @@
1
+ import { type CheckDef } from '../core/check-def';
2
+ export declare const numberChecks: {
3
+ isGreaterThan: CheckDef<number>;
4
+ isAtLeast: CheckDef<number>;
5
+ isLessThan: CheckDef<number>;
6
+ isAtMost: CheckDef<number>;
7
+ isBetween: CheckDef<readonly [number, number]>;
8
+ isPositive: CheckDef<boolean>;
9
+ isNegative: CheckDef<boolean>;
10
+ isMultipleOf: CheckDef<number>;
11
+ };
@@ -0,0 +1,9 @@
1
+ import type { AffirmParams } from '../types/params';
2
+ export declare const objectChecks: {
3
+ shape: import("../core/check-def").CheckDef<Readonly<Record<string, AffirmParams>>>;
4
+ hasKey: import("../core/check-def").CheckDef<PropertyKey>;
5
+ hasKeys: import("../core/check-def").CheckDef<readonly PropertyKey[]>;
6
+ hasAnyKey: import("../core/check-def").CheckDef<readonly PropertyKey[]>;
7
+ hasOnlyKeys: import("../core/check-def").CheckDef<readonly PropertyKey[]>;
8
+ hasPath: import("../core/check-def").CheckDef<string>;
9
+ };
@@ -0,0 +1,14 @@
1
+ import { type CheckDef } from '../core/check-def';
2
+ import { type StandardSchemaV1 } from '../core/util/standard-schema';
3
+ import type { TypeGuard, TypeTag } from '../types/runtime-type';
4
+ export declare const runtimeTypeChecks: {
5
+ isType: CheckDef<StandardSchemaV1<unknown, unknown> | TypeGuard | TypeTag>;
6
+ isArray: CheckDef<boolean>;
7
+ isPlainObject: CheckDef<boolean>;
8
+ isFunction: CheckDef<boolean>;
9
+ isInstanceOf: CheckDef<abstract new (...args: any) => any>;
10
+ isValidDate: CheckDef<boolean>;
11
+ isInteger: CheckDef<boolean>;
12
+ isFiniteNumber: CheckDef<boolean>;
13
+ isNaN: CheckDef<boolean>;
14
+ };
@@ -0,0 +1,8 @@
1
+ export declare const sizeChecks: {
2
+ isEmpty: import("../core/check-def").CheckDef<boolean>;
3
+ isNotEmpty: import("../core/check-def").CheckDef<boolean>;
4
+ isBlank: import("../core/check-def").CheckDef<boolean>;
5
+ hasLength: import("../core/check-def").CheckDef<number>;
6
+ hasMinLength: import("../core/check-def").CheckDef<number>;
7
+ hasMaxLength: import("../core/check-def").CheckDef<number>;
8
+ };
@@ -0,0 +1,6 @@
1
+ export declare const stringChecks: {
2
+ startsWith: import("../core/check-def").CheckDef<string>;
3
+ endsWith: import("../core/check-def").CheckDef<string>;
4
+ includes: import("../core/check-def").CheckDef<string>;
5
+ matches: import("../core/check-def").CheckDef<RegExp>;
6
+ };
@@ -0,0 +1,93 @@
1
+ import type { AffirmParams } from '../types/params';
2
+ import { type AffirmFailure } from './report';
3
+ /** Canonical evaluation phases (design §4 rule 7). Lower runs first. */
4
+ export declare const Phase: {
5
+ /** Cheap type / nullish / equality checks. */
6
+ readonly Kind: 0;
7
+ /** Size, number and string checks. */
8
+ readonly Measure: 1;
9
+ /** Structural checks: shape, everyItem, isDeepEqual, … */
10
+ readonly Structural: 2;
11
+ /** User predicates: satisfies. */
12
+ readonly Predicate: 3;
13
+ };
14
+ export type Phase = (typeof Phase)[keyof typeof Phase];
15
+ export type Mode = 'first' | 'all';
16
+ export interface EvalContext {
17
+ /** The params key being evaluated. */
18
+ readonly key: string;
19
+ /** Path of the value being checked; `''` at the root. */
20
+ readonly path: string;
21
+ /** `'first'` for `affirm()` (short-circuit), `'all'` for `explain()` (collect everything). */
22
+ readonly mode: Mode;
23
+ /** Recursion for composite keys: failures of nested params, in the current mode. Params must already be validated. */
24
+ run(value: unknown, params: AffirmParams, path: string): AffirmFailure[];
25
+ /** Pass/fail of nested params, always short-circuiting. For `not` and `someItem`. */
26
+ test(value: unknown, params: AffirmParams): boolean;
27
+ }
28
+ /** Validates nested params (throws `TypeError`). Passed to composite keys so checks don't import the engine. */
29
+ export type ValidateNested = (params: unknown, path: string) => void;
30
+ export interface CheckDef<Param> {
31
+ readonly phase: Phase;
32
+ /**
33
+ * Programmer-error guard (design §4 rule 6). Returns `undefined` when the param is valid,
34
+ * otherwise a description of what was expected, e.g. `'a non-negative integer'`.
35
+ * Composite keys validate their nested params with `validateNested`.
36
+ */
37
+ validateParam(param: unknown, path: string, validateNested: ValidateNested): string | undefined;
38
+ /** Returns `[]` on pass. */
39
+ evaluate(value: unknown, param: Param, ctx: EvalContext): AffirmFailure[];
40
+ }
41
+ /** A group's runtime object: exactly one `CheckDef` per key of its params interface. */
42
+ export type CheckGroup<P> = {
43
+ readonly [K in keyof P]-?: CheckDef<Exclude<P[K], undefined>>;
44
+ };
45
+ /** Optional kind gate: if `accepts` fails, one failure is reported and `test` never runs (rule 5, D7). */
46
+ interface Gate<V> {
47
+ accepts?: (value: unknown) => value is V;
48
+ /** Shown as `expected` when the gate fails, e.g. `'a number'`. */
49
+ acceptsLabel?: string;
50
+ }
51
+ export interface LeafSpec<P, V> extends Gate<V> {
52
+ phase: Phase;
53
+ validateParam: (param: unknown) => string | undefined;
54
+ test: (value: V, param: P) => boolean;
55
+ expected: (param: P) => string;
56
+ }
57
+ /** Builds a check from a plain `(value, param) => boolean` test. */
58
+ export declare function leaf<P, V = unknown>(spec: LeafSpec<P, V>): CheckDef<P>;
59
+ export interface BooleanLeafSpec<V> extends Gate<V> {
60
+ phase: Phase;
61
+ test: (value: V) => boolean;
62
+ /** `expected` when the param is `true`, e.g. `'null'`. */
63
+ expected: string;
64
+ /** `expected` when the param is `false`, e.g. `'not null'`. */
65
+ expectedNot: string;
66
+ }
67
+ /**
68
+ * Builds a boolean key. Implements D1 once: pass ⇔ `test(value) === param`.
69
+ * The kind gate (if any) runs first and fails for both polarities (D7).
70
+ */
71
+ export declare function booleanLeaf<V = unknown>(spec: BooleanLeafSpec<V>): CheckDef<boolean>;
72
+ export interface CompositeSpec<P, V> extends Gate<V> {
73
+ phase: Phase;
74
+ validateParam: (param: unknown, path: string, validateNested: ValidateNested) => string | undefined;
75
+ /** Called only when the gate passes. Returns `[]` on pass. */
76
+ evaluate: (value: V, param: P, ctx: EvalContext) => AffirmFailure[];
77
+ }
78
+ /**
79
+ * Builds a composite key (shape, everyItem, anyOf, …). The kind gate runs first, so a value of the
80
+ * wrong kind produces ONE failure instead of one per child (design §4 rule 7).
81
+ */
82
+ export declare function composite<P, V = unknown>(spec: CompositeSpec<P, V>): CheckDef<P>;
83
+ /** `{ isNull: true, hasKey: "id" }`: a short rendering of nested params for `expected`. */
84
+ export declare function formatParams(params: AffirmParams): string;
85
+ export declare const anyParam: () => undefined;
86
+ export declare const arrayParam: (param: unknown) => string | undefined;
87
+ export declare const functionParam: (param: unknown) => string | undefined;
88
+ export declare const numberParam: (param: unknown) => string | undefined;
89
+ export declare const nonNegativeIntegerParam: (param: unknown) => string | undefined;
90
+ export declare const stringParam: (param: unknown) => string | undefined;
91
+ export declare const propertyKeyParam: (param: unknown) => string | undefined;
92
+ export declare const propertyKeyListParam: (param: unknown) => string | undefined;
93
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Describes a value by type and size only, never by content (design §8, D5).
3
+ * Used for `AffirmFailure.received`.
4
+ */
5
+ export declare function describe(value: unknown): string;
6
+ /**
7
+ * Formats a *param* (authored in code, not data) for `expected`.
8
+ * Short strings and primitives are shown literally; anything else is described.
9
+ */
10
+ export declare function formatParam(param: unknown): string;
11
+ export declare function formatList(list: readonly unknown[]): string;
@@ -0,0 +1,18 @@
1
+ import type { AffirmReport } from './report';
2
+ /**
3
+ * Thrown by `affirm.assert` when data fails its checks (design §9). `report` has every failure.
4
+ * The default message lists the first three reasons, then `(+N more)`.
5
+ *
6
+ * @example
7
+ * try {
8
+ * affirm.assert(body, { shape: { email: { matches: /@/ } } })
9
+ * } catch (error) {
10
+ * if (error instanceof AffirmError) return badRequest(error.report.failures)
11
+ * throw error
12
+ * }
13
+ */
14
+ export declare class AffirmError extends Error {
15
+ readonly name = "AffirmError";
16
+ readonly report: AffirmReport;
17
+ constructor(report: AffirmReport, message?: string);
18
+ }
@@ -0,0 +1,8 @@
1
+ import type { AffirmParams } from '../types/params';
2
+ import type { Mode } from './check-def';
3
+ import type { AffirmFailure } from './report';
4
+ /**
5
+ * Runs already-validated params against a value in canonical key order (design §4 rule 7).
6
+ * `'first'` stops at the first failing key; `'all'` collects every failure.
7
+ */
8
+ export declare function runParams(value: unknown, params: AffirmParams, path: string, mode: Mode): AffirmFailure[];
@@ -0,0 +1,18 @@
1
+ import type { AffirmParams } from '../types/params';
2
+ import type { CheckDef, CheckGroup } from './check-def';
3
+ type AnyGroup = Readonly<Record<string, CheckDef<any>>>;
4
+ type UnionToIntersection<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void ? I : never;
5
+ /**
6
+ * Merges group objects into one registry. Throws at module load on a duplicate key,
7
+ * which a plain spread would silently overwrite.
8
+ */
9
+ export declare function defineRegistry<const G extends readonly AnyGroup[]>(...groups: G): UnionToIntersection<G[number]>;
10
+ /** Every check, keyed by params key. Group order here is the tie-breaker within a phase. */
11
+ export declare const checks: CheckGroup<AffirmParams>;
12
+ export type CheckKey = keyof AffirmParams;
13
+ /** All keys, sorted by phase (stable, so registry order breaks ties). Design §4 rule 7. */
14
+ export declare const KEY_ORDER: readonly CheckKey[];
15
+ export declare function isCheckKey(key: string): key is CheckKey;
16
+ /** Canonical rank of a key; only call with keys that passed `isCheckKey`. */
17
+ export declare function rankOf(key: CheckKey): number;
18
+ export {};
@@ -0,0 +1,22 @@
1
+ /** One failed check. Never contains raw values from the checked data (design §8, D5). */
2
+ export interface AffirmFailure {
3
+ /** The params key that failed, e.g. `'hasMinLength'`. */
4
+ key: string;
5
+ /** `''` at the root; `'user.address.zip'`; `'items[2].id'`. */
6
+ path: string;
7
+ /** What the check wanted, e.g. `'length >= 3'`, `'not null'`. */
8
+ expected: string;
9
+ /** A type description of the value, e.g. `'string(len 2)'`. */
10
+ received: string;
11
+ /** One human sentence combining path, expected and received. */
12
+ reason: string;
13
+ /** For `anyOf`: the failures of each branch. */
14
+ branches?: AffirmFailure[][];
15
+ }
16
+ export interface AffirmReport {
17
+ ok: boolean;
18
+ failures: AffirmFailure[];
19
+ }
20
+ export declare function makeFailure(key: string, path: string, expected: string, value: unknown): AffirmFailure;
21
+ /** `joinPath('items', 2)` → `'items[2]'`; `joinPath('user', 'zip')` → `'user.zip'`. */
22
+ export declare function joinPath(base: string, segment: string | number): string;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Structural equality per design §7.
3
+ * - primitives: `Object.is`, except `+0` equals `-0`
4
+ * - arrays: same length, elementwise
5
+ * - plain objects: same own enumerable string keys, valuewise
6
+ * - Date: same time · RegExp: same source + flags
7
+ * - Map: same size, same keys (SameValueZero), values deep-equal
8
+ * - Set: same size, every member present (SameValueZero; no deep matching of members)
9
+ * - other class instances: reference equality only
10
+ * - cycles: a pair already under comparison counts as equal
11
+ */
12
+ export declare function deepEqual(a: unknown, b: unknown): boolean;