@asd14/m 10.0.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,20 @@
1
1
  type EscapeHTMLFn = (input: string) => string;
2
2
  /**
3
- * Escape HTML special characters in a string so it can be safely embedded
4
- * in an HTML document without being interpreted as markup.
3
+ * Escape the HTML special characters of a string, `"&'/<>`, so it can be
4
+ * embedded as text: in element content, eg. `<p>…</p>`.
5
+ *
6
+ * It is not safe anywhere else:
7
+ *
8
+ * - an unquoted attribute value: a space starts a new attribute, eg.
9
+ * `<input value=${escapeHTML("x onfocus=alert(1)")}>`
10
+ * - an event handler, eg. `onclick`: its value is code, so the text runs,
11
+ * eg. `alert(1)`. The browser also decodes `&#39;` back to `'` first
12
+ * - a URL attribute, eg. `href` or `src`: `javascript:alert(1)` comes back
13
+ * unchanged. Allow only some schemes, eg. `https:`, and encode a part of
14
+ * the URL with `encodeURIComponent`
15
+ * - the content of `<script>` or `<style>`: they decode no entities, so the
16
+ * text runs as code. Use `JSON.stringify` for a value in a script, and
17
+ * `CSS.escape` for a CSS value
5
18
  *
6
19
  * Input is never mutated - always returns a new string.
7
20
  *
@@ -10,6 +23,8 @@ type EscapeHTMLFn = (input: string) => string;
10
23
  * @returns {string} String with HTML special characters escaped
11
24
  *
12
25
  * @example
26
+ * `<p>${escapeHTML(bio)}</p>`
27
+ *
13
28
  * escapeHTML("<b>bold</b>")
14
29
  * // => "&lt;b&gt;bold&lt;&#47;b&gt;"
15
30
  *
@@ -9,8 +9,21 @@ const CHAR_MAP = {
9
9
  };
10
10
  const HTML_SPECIAL = /["&'/<>]/g;
11
11
  /**
12
- * Escape HTML special characters in a string so it can be safely embedded
13
- * in an HTML document without being interpreted as markup.
12
+ * Escape the HTML special characters of a string, `"&'/<>`, so it can be
13
+ * embedded as text: in element content, eg. `<p>…</p>`.
14
+ *
15
+ * It is not safe anywhere else:
16
+ *
17
+ * - an unquoted attribute value: a space starts a new attribute, eg.
18
+ * `<input value=${escapeHTML("x onfocus=alert(1)")}>`
19
+ * - an event handler, eg. `onclick`: its value is code, so the text runs,
20
+ * eg. `alert(1)`. The browser also decodes `&#39;` back to `'` first
21
+ * - a URL attribute, eg. `href` or `src`: `javascript:alert(1)` comes back
22
+ * unchanged. Allow only some schemes, eg. `https:`, and encode a part of
23
+ * the URL with `encodeURIComponent`
24
+ * - the content of `<script>` or `<style>`: they decode no entities, so the
25
+ * text runs as code. Use `JSON.stringify` for a value in a script, and
26
+ * `CSS.escape` for a CSS value
14
27
  *
15
28
  * Input is never mutated - always returns a new string.
16
29
  *
@@ -19,6 +32,8 @@ const HTML_SPECIAL = /["&'/<>]/g;
19
32
  * @returns {string} String with HTML special characters escaped
20
33
  *
21
34
  * @example
35
+ * `<p>${escapeHTML(bio)}</p>`
36
+ *
22
37
  * escapeHTML("<b>bold</b>")
23
38
  * // => "&lt;b&gt;bold&lt;&#47;b&gt;"
24
39
  *
@@ -1,43 +1,45 @@
1
1
  import type { PlainObject } from "../../types/object.js";
2
2
  type DeepFlatten<T> = T extends readonly (infer U)[] ? DeepFlatten<U> : T;
3
3
  type FlattenLevel<T, Level extends number, Depth extends unknown[] = []> = number extends Level ? unknown : T extends readonly (infer U)[] ? Depth["length"] extends Level ? T : FlattenLevel<U, Level, [...Depth, unknown]> : T;
4
- type FlattenObjectOptions = {
5
- separator: string;
6
- };
4
+ type FlattenInputFor<LevelOrSeparator> = LevelOrSeparator extends number ? readonly unknown[] : LevelOrSeparator extends string ? PlainObject : never;
5
+ type FlattenOne<First> = First extends number ? <T>(input: readonly T[]) => FlattenLevel<T, First>[] : First extends string ? (input: PlainObject) => PlainObject : First extends readonly (infer T)[] ? DeepFlatten<T>[] : First extends PlainObject ? PlainObject : never;
7
6
  type FlattenFn = {
8
- <T, const Level extends number>(options: {
9
- level: Level;
10
- }, input: readonly T[]): FlattenLevel<T, Level>[];
11
- (options: FlattenObjectOptions, input: PlainObject): PlainObject;
12
- <T>(input: readonly T[]): DeepFlatten<T>[];
13
- (input: PlainObject): PlainObject;
7
+ <First extends number | string | readonly unknown[] | PlainObject>(levelSeparatorOrInput: First): FlattenOne<First>;
8
+ <LevelOrSeparator extends number | string, I extends FlattenInputFor<LevelOrSeparator>>(levelOrSeparator: LevelOrSeparator, input: I): LevelOrSeparator extends number ? I extends readonly (infer T)[] ? FlattenLevel<T, LevelOrSeparator>[] : never : LevelOrSeparator extends string ? PlainObject : never;
14
9
  };
15
10
  /**
16
- * Recursively flatten nested arrays or objects.
11
+ * Flatten nested arrays or objects.
17
12
  *
18
- * For arrays, concatenates all nested arrays into a single flat array.
13
+ * For arrays, concatenates nested arrays into a single flat array, down to
14
+ * `level` levels.
19
15
  * For objects, joins nested keys with a separator into a flat structure.
20
16
  *
21
- * It recurses, so the stack limits the depth: an object nested a few thousand
22
- * levels deep throws a `RangeError`. `JSON.parse` accepts any depth, so check
23
- * the depth of untrusted input first, if it can be that deep.
17
+ * It recurses, so the stack limits the depth: an array or an object nested a
18
+ * few thousand levels deep throws a `RangeError`. `JSON.parse` accepts any
19
+ * depth, so check the depth of untrusted input first, if it can be that deep.
24
20
  *
25
21
  * Input is never mutated - always returns a new array or object.
26
22
  *
27
23
  * Only a plain object is flattened. An empty object, a `Date`, a `Map` and a
28
- * class instance stay as values, and so does an object that contains itself.
29
- * `level` counts the array levels to flatten, `Infinity` by default.
24
+ * class instance stay as values. An array or an object that contains itself
25
+ * stays as a value too.
30
26
  *
31
- * Options go only in the two-argument form. With one argument, `flatten`
32
- * flattens it, even an object with a `level` or `separator` key.
27
+ * A number before an array is the level, the number of array levels to
28
+ * flatten, `Infinity` by default. For all levels, call `flatten(input)`:
29
+ * `Infinity` is a `number` to TypeScript, so `flatten(Infinity, input)` returns
30
+ * `unknown[]`. A string before an object is the separator, `"."` by default.
31
+ * With either alone, `flatten` returns a pipe step. One object alone is the
32
+ * input, even with a `level` or `separator` key.
33
33
  *
34
- * @param {Object} [options] - { level: number } for arrays, { separator: string } for objects
34
+ * @param {number|string} [levelOrSeparator] - The level for an array, or the separator for an object
35
35
  * @param {Array|Object} input - Array or object to flatten
36
36
  *
37
37
  * @returns {Array|Object} Flattened result
38
38
  *
39
39
  * @throws {TypeError} When two entries flatten to the same key, eg. the key
40
- * `"user.role"` next to `{ user: { role } }`
40
+ * `"user.role"` next to `{ user: { role } }`:
41
+ * `@asd14/m/flatten: expected 'user.role' to be 'Unique', got 'Duplicate'`
42
+ * @throws {RangeError} When the input is nested deeper than the stack allows
41
43
  *
42
44
  * @example
43
45
  * flatten([1, [2], [3, [4]]])
@@ -46,26 +48,29 @@ type FlattenFn = {
46
48
  * flatten({ a: { b: 1, c: { d: 2 } } })
47
49
  * // => { "a.b": 1, "a.c.d": 2 }
48
50
  *
49
- * flatten({ level: 1 }, [1, [2, [3]]])
51
+ * flatten(1, [1, [2, [3]]])
50
52
  * // => [1, 2, [3]]
51
53
  *
52
- * flatten({ separator: "__" }, { a: { b: 1 } })
54
+ * flatten("__", { a: { b: 1 } })
53
55
  * // => { a__b: 1 }
54
56
  *
57
+ * pipe(read("tags"), flatten(1))({
58
+ * tags: [[1], [2, [3]]]
59
+ * })
60
+ * // => [1, 2, [3]]
61
+ *
62
+ * pipe(read("meta"), flatten("/"))({
63
+ * meta: { a: { b: 1 } }
64
+ * })
65
+ * // => { "a/b": 1 }
66
+ *
55
67
  * flatten({ a: {}, b: { c: new Date(0) } })
56
68
  * // => { a: {}, "b.c": new Date(0) }
57
69
  *
58
- * pipe(
59
- * map(read("tags")),
60
- * flatten,
61
- * distinct
62
- * )([{ tags: ["a"] }, { tags: ["a", "b"] }])
63
- * // => ["a", "b"]
64
- *
65
70
  * @name flatten
66
71
  * @tag Array
67
72
  *
68
- * @see {@link unflatten}
73
+ * @see {@link unflatten} to rebuild the nested object from the flat keys
69
74
  */
70
75
  declare const flatten: FlattenFn;
71
76
  export { flatten };
@@ -2,16 +2,19 @@ import { isPlainObject } from "../is/is.js";
2
2
  import { type } from "../type/type.js";
3
3
  import { _setOwn } from "../utils/set-own.js";
4
4
  // Pushes into `result`: a spread of a large child array into `push` would
5
- // overflow the call stack
6
- const _flattenArray = (input, level, result = [])=>{
5
+ // overflow the call stack. `ancestors` holds the arrays above `input`: an
6
+ // array that contains itself is kept as an item, as in `_flattenObject`
7
+ const _flattenArray = (input, level, result = [], ancestors = new WeakSet())=>{
8
+ ancestors.add(input);
7
9
  for(let i = 0, length = input.length; i < length; i++){
8
10
  const item = input[i];
9
- if (level > 0 && Array.isArray(item)) {
10
- _flattenArray(item, level - 1, result);
11
+ if (level > 0 && Array.isArray(item) && !ancestors.has(item)) {
12
+ _flattenArray(item, level - 1, result, ancestors);
11
13
  } else {
12
14
  result.push(item);
13
15
  }
14
16
  }
17
+ ancestors.delete(input);
15
18
  return result;
16
19
  };
17
20
  // `ancestors` holds the objects above `input`: an object that contains itself
@@ -40,36 +43,61 @@ const _flattenObject = (input, separator, prefix, result, ancestors)=>{
40
43
  return result;
41
44
  };
42
45
  const _flatten = (input, level, separator)=>{
43
- if (Array.isArray(input)) return _flattenArray(input, level);
44
- if (isPlainObject(input)) return _flattenObject(input, separator, undefined, {}, new WeakSet());
46
+ if (Array.isArray(input)) {
47
+ return _flattenArray(input, level);
48
+ }
49
+ if (isPlainObject(input)) {
50
+ return _flattenObject(input, separator, undefined, {}, new WeakSet());
51
+ }
45
52
  throw new TypeError(`@asd14/m/flatten: expected 'input' to be 'Array' or 'Object', got '${type(input)}'`);
46
53
  };
54
+ // Flatten `level` levels of an array
55
+ const _flattenLevels = (level, input)=>{
56
+ if (!Array.isArray(input)) {
57
+ throw new TypeError(`@asd14/m/flatten: expected 'input' to be 'Array', got '${type(input)}'`);
58
+ }
59
+ return _flattenArray(input, level);
60
+ };
61
+ // Flatten the keys of an object, joined with `separator`
62
+ const _flattenKeys = (separator, input)=>{
63
+ if (!isPlainObject(input)) {
64
+ throw new TypeError(`@asd14/m/flatten: expected 'input' to be 'Object', got '${type(input)}'`);
65
+ }
66
+ return _flattenObject(input, separator, undefined, {}, new WeakSet());
67
+ };
47
68
  /**
48
- * Recursively flatten nested arrays or objects.
69
+ * Flatten nested arrays or objects.
49
70
  *
50
- * For arrays, concatenates all nested arrays into a single flat array.
71
+ * For arrays, concatenates nested arrays into a single flat array, down to
72
+ * `level` levels.
51
73
  * For objects, joins nested keys with a separator into a flat structure.
52
74
  *
53
- * It recurses, so the stack limits the depth: an object nested a few thousand
54
- * levels deep throws a `RangeError`. `JSON.parse` accepts any depth, so check
55
- * the depth of untrusted input first, if it can be that deep.
75
+ * It recurses, so the stack limits the depth: an array or an object nested a
76
+ * few thousand levels deep throws a `RangeError`. `JSON.parse` accepts any
77
+ * depth, so check the depth of untrusted input first, if it can be that deep.
56
78
  *
57
79
  * Input is never mutated - always returns a new array or object.
58
80
  *
59
81
  * Only a plain object is flattened. An empty object, a `Date`, a `Map` and a
60
- * class instance stay as values, and so does an object that contains itself.
61
- * `level` counts the array levels to flatten, `Infinity` by default.
82
+ * class instance stay as values. An array or an object that contains itself
83
+ * stays as a value too.
62
84
  *
63
- * Options go only in the two-argument form. With one argument, `flatten`
64
- * flattens it, even an object with a `level` or `separator` key.
85
+ * A number before an array is the level, the number of array levels to
86
+ * flatten, `Infinity` by default. For all levels, call `flatten(input)`:
87
+ * `Infinity` is a `number` to TypeScript, so `flatten(Infinity, input)` returns
88
+ * `unknown[]`. A string before an object is the separator, `"."` by default.
89
+ * With either alone, `flatten` returns a pipe step. One object alone is the
90
+ * input, even with a `level` or `separator` key.
65
91
  *
66
- * @param {Object} [options] - { level: number } for arrays, { separator: string } for objects
92
+ * @param {number|string} [levelOrSeparator] - The level for an array, or the separator for an object
67
93
  * @param {Array|Object} input - Array or object to flatten
68
94
  *
69
95
  * @returns {Array|Object} Flattened result
70
96
  *
71
97
  * @throws {TypeError} When two entries flatten to the same key, eg. the key
72
- * `"user.role"` next to `{ user: { role } }`
98
+ * `"user.role"` next to `{ user: { role } }`:
99
+ * `@asd14/m/flatten: expected 'user.role' to be 'Unique', got 'Duplicate'`
100
+ * @throws {RangeError} When the input is nested deeper than the stack allows
73
101
  *
74
102
  * @example
75
103
  * flatten([1, [2], [3, [4]]])
@@ -78,43 +106,60 @@ const _flatten = (input, level, separator)=>{
78
106
  * flatten({ a: { b: 1, c: { d: 2 } } })
79
107
  * // => { "a.b": 1, "a.c.d": 2 }
80
108
  *
81
- * flatten({ level: 1 }, [1, [2, [3]]])
109
+ * flatten(1, [1, [2, [3]]])
82
110
  * // => [1, 2, [3]]
83
111
  *
84
- * flatten({ separator: "__" }, { a: { b: 1 } })
112
+ * flatten("__", { a: { b: 1 } })
85
113
  * // => { a__b: 1 }
86
114
  *
115
+ * pipe(read("tags"), flatten(1))({
116
+ * tags: [[1], [2, [3]]]
117
+ * })
118
+ * // => [1, 2, [3]]
119
+ *
120
+ * pipe(read("meta"), flatten("/"))({
121
+ * meta: { a: { b: 1 } }
122
+ * })
123
+ * // => { "a/b": 1 }
124
+ *
87
125
  * flatten({ a: {}, b: { c: new Date(0) } })
88
126
  * // => { a: {}, "b.c": new Date(0) }
89
127
  *
90
- * pipe(
91
- * map(read("tags")),
92
- * flatten,
93
- * distinct
94
- * )([{ tags: ["a"] }, { tags: ["a", "b"] }])
95
- * // => ["a", "b"]
96
- *
97
128
  * @name flatten
98
129
  * @tag Array
99
130
  *
100
- * @see {@link unflatten}
131
+ * @see {@link unflatten} to rebuild the nested object from the flat keys
101
132
  */ const flatten = (...params)=>{
102
- // @signature (input)
133
+ const [first, input] = params;
134
+ // A number is the level, for an array. A string is the separator, for an
135
+ // object. Neither can be the input, so one argument of either is a pipe step
103
136
  if (params.length === 1) {
104
- return _flatten(params[0], Infinity, ".");
137
+ // @signature (level) => (input)
138
+ if (typeof first === "number") {
139
+ return (input)=>_flattenLevels(first, input);
140
+ }
141
+ // @signature (separator) => (input)
142
+ if (typeof first === "string") {
143
+ return (input)=>_flattenKeys(first, input);
144
+ }
145
+ // @signature (input)
146
+ return _flatten(first, Infinity, ".");
147
+ }
148
+ // @signature (level, input)
149
+ if (typeof first === "number") {
150
+ return _flattenLevels(first, input);
105
151
  }
106
- const options = params[0];
107
- if (!isPlainObject(options)) {
108
- throw new TypeError(`@asd14/m/flatten: expected 'options' to be 'Object', got '${type(options)}'`);
152
+ // @signature (separator, input)
153
+ if (typeof first === "string") {
154
+ return _flattenKeys(first, input);
109
155
  }
110
- const { level = Infinity, separator = "." } = options;
111
- if (typeof level !== "number") {
112
- throw new TypeError(`@asd14/m/flatten: expected 'level' to be 'Number', got '${type(level)}'`);
156
+ // Name the argument the input asks for, eg. for the options object of 10.x
157
+ if (Array.isArray(input)) {
158
+ throw new TypeError(`@asd14/m/flatten: expected 'level' to be 'Number', got '${type(first)}'`);
113
159
  }
114
- if (typeof separator !== "string") {
115
- throw new TypeError(`@asd14/m/flatten: expected 'separator' to be 'String', got '${type(separator)}'`);
160
+ if (isPlainObject(input)) {
161
+ throw new TypeError(`@asd14/m/flatten: expected 'separator' to be 'String', got '${type(first)}'`);
116
162
  }
117
- // @signature (options, input)
118
- return _flatten(params[1], level, separator);
163
+ return _flatten(input, Infinity, ".");
119
164
  };
120
165
  export { flatten };
@@ -10,6 +10,10 @@ type IsMatchFn = {
10
10
  * a pipe of functions, never a value: match an array with a predicate. Reads
11
11
  * only the own keys of the input.
12
12
  *
13
+ * For each key of `match`, `isMatch` reads the input's value under that key,
14
+ * `undefined` when the input lacks it, and compares the two. So
15
+ * `{ ownerId: undefined }` matches an object that has no `ownerId`.
16
+ *
13
17
  * @param {Object} match - Subset of properties to test against
14
18
  * @param {Object} input - Object to test
15
19
  *
@@ -6,6 +6,10 @@ import { _buildMatch } from "../utils/build-match.js";
6
6
  * a pipe of functions, never a value: match an array with a predicate. Reads
7
7
  * only the own keys of the input.
8
8
  *
9
+ * For each key of `match`, `isMatch` reads the input's value under that key,
10
+ * `undefined` when the input lacks it, and compares the two. So
11
+ * `{ ownerId: undefined }` matches an object that has no `ownerId`.
12
+ *
9
13
  * @param {Object} match - Subset of properties to test against
10
14
  * @param {Object} input - Object to test
11
15
  *
@@ -1,11 +1,10 @@
1
+ import type { ToArray } from "../../types/array.js";
1
2
  import type { DeepWrite } from "../../types/object.js";
2
3
  type WritePath = readonly [string | number, ...(string | number)[]];
3
4
  type WriteValue = string | number | boolean | bigint | symbol | object | null | undefined;
4
5
  type WriteFn = {
5
- <I extends object, const P extends WritePath, V extends WriteValue>(path: P, value: V, input: I): DeepWrite<I, P, V>;
6
- <const P extends WritePath, V extends WriteValue>(path: P, value: V): <I extends object>(input: I) => DeepWrite<I, P, V>;
7
- <I extends object, K extends string, V extends WriteValue>(path: K, value: V, input: I): DeepWrite<I, [K], V>;
8
- <K extends string, V extends WriteValue>(path: K, value: V): <I extends object>(input: I) => DeepWrite<I, [K], V>;
6
+ <I extends object, const P extends string | WritePath, V extends WriteValue>(path: P, value: V, input: I): DeepWrite<I, ToArray<P>, V>;
7
+ <const P extends string | WritePath, V extends WriteValue>(path: P, value: V): <I extends object>(input: I) => DeepWrite<I, ToArray<P>, V>;
9
8
  };
10
9
  /**
11
10
  * Write a value at a key or a deep path. Creates each missing step: an array
@@ -23,3 +23,15 @@ export type Rest<I extends unknown[]> = I extends [
23
23
  first: unknown,
24
24
  ...rest: infer O
25
25
  ] ? O : never;
26
+ /**
27
+ * Wrap a value that is not an array into a tuple of one. An array passes as it
28
+ * is.
29
+ *
30
+ * @example
31
+ * type Path = ToArray<"name">
32
+ * // => ["name"]
33
+ *
34
+ * type Same = ToArray<["user", "name"]>
35
+ * // => ["user", "name"]
36
+ */
37
+ export type ToArray<T> = T extends readonly unknown[] ? T : [T];
@@ -2,7 +2,8 @@ import type { PredicatePipe, UnaryPredicate } from "./function.js";
2
2
  import type { PlainObject } from "./object.js";
3
3
  /**
4
4
  * A match condition applied to a single object key. Either:
5
- * - a literal value to compare with strict equality
5
+ * - a literal value, compared with SameValueZero, as `isEqual`, with the
6
+ * input's value under the key, `undefined` when the input lacks it
6
7
  * - `null` for null-checking
7
8
  * - a predicate `(value: V) => boolean`
8
9
  * - a pipe chain ending in a predicate (`V → ... → boolean`)
@@ -12,7 +13,8 @@ type KeyMatcher<V> = Exclude<V, readonly unknown[]> | null | UnaryPredicate<V> |
12
13
  * A map of key-level matchers. Each key maps to a value, predicate,
13
14
  * or predicate pipe chain. Supports negation keys prefixed with "!".
14
15
  *
15
- * Used by `isMatch` — tests whether an object satisfies all conditions.
16
+ * Used by `isMatch` and every `*With` function, eg. `filterWith`, the same way
17
+ * in each — tests whether an object satisfies all conditions.
16
18
  */
17
19
  type Matcher<T extends PlainObject> = {
18
20
  [K in keyof T]?: T[K] extends never ? unknown : KeyMatcher<T[K]>;
package/docs/SPEC.md CHANGED
@@ -17,16 +17,16 @@ is to route data to a step is effort: the data still flows, but with a nudge.
17
17
  // Effortless: each step takes the output of the step above
18
18
  pipe(
19
19
  read("tags"),
20
- flatten
20
+ flatten(1)
21
21
  )({
22
- tags: [[1], [2, [3]]]
22
+ tags: [[1], [2, [3]]]
23
23
  })
24
- // => [1, 2, 3]
24
+ // => [1, 2, [3]]
25
25
 
26
- // Effort: a lambda routes `tags` into the options form
26
+ // Effort: a lambda routes `tags` into a method
27
27
  pipe(
28
28
  read("tags"),
29
- tags => flatten({ level: 1 }, tags)
29
+ tags => tags.flat(1)
30
30
  )({
31
31
  tags: [[1], [2, [3]]]
32
32
  })
@@ -23,9 +23,6 @@ does this function do, what goes in, what comes out, how to use it.
23
23
  * partition(x => x % 2 === 0, [1, 2, 3, 4, 5])
24
24
  * // => [[2, 4], [1, 3, 5]]
25
25
  *
26
- * partition(x => x > 3)([1, 2, 3, 4, 5])
27
- * // => [[4, 5], [1, 2, 3]]
28
- *
29
26
  * partition([read("comments"), isSomething], items)
30
27
  * // => [[{ id: 1, comments: [] }], [{ id: 2 }]]
31
28
  *
@@ -38,9 +35,9 @@ does this function do, what goes in, what comes out, how to use it.
38
35
  * @name partition
39
36
  * @tag Array
40
37
  *
41
- * @see {@link partitionWith}
42
- * @see {@link filter}
43
- * @see {@link filterWith}
38
+ * @see {@link partitionWith} to split by a matcher
39
+ * @see {@link filter} to keep only the items that pass
40
+ * @see {@link filterWith} to keep only the items that match
44
41
  */
45
42
  ```
46
43
 
@@ -60,27 +57,49 @@ does this function do, what goes in, what comes out, how to use it.
60
57
 
61
58
  ### `@example`
62
59
 
63
- Examples are ordered by complexity, each one teaching a new calling convention:
60
+ Show one example per call pattern: each overload of the function's `*Fn` type,
61
+ in this order:
62
+
63
+ 1. **Input only**: a one-argument call that runs with the defaults, eg.
64
+ `flatten(input)`
65
+ 2. **Uncurried**: each overload with the input last, eg. `flatten(1, input)` and
66
+ `flatten("/", input)`
67
+ 3. **Curried**: each overload that returns a pipe step, shown inside `pipe`, eg.
68
+ `pipe(read("tags"), flatten(1))`
69
+ 4. **Behaviour a reader cannot guess** from the types, eg. a `Date` stays a leaf
64
70
 
65
- 1. **Uncurried** - simplest call, plain function + input
66
- 2. **Curried** - same function, split into two calls
67
- 3. **Predicate pipe / advanced** - shows composition with other primitives
68
- 4. **`pipe` integration** - always last, shows how the function fits in a
69
- pipeline
71
+ A reader who reads the examples top to bottom knows every way to call the
72
+ function. To check, count the overloads and the examples.
70
73
 
71
74
  Each example shows the concrete return value as a `// =>` comment. The user
72
75
  should be able to read the examples top-to-bottom and understand every way to
73
76
  call the function.
74
77
 
78
+ ### `@throws`
79
+
80
+ Add one for each error a valid-looking call can throw, with an example of its
81
+ message:
82
+
83
+ ```ts
84
+ @throws {TypeError} When two entries flatten to the same key, eg. the key
85
+ `"user.role"` next to `{ user: { role } }`
86
+ ```
87
+
88
+ Leave out the guards every function has, eg. a number where an array goes: the
89
+ types catch those first.
90
+
75
91
  ### `@see`
76
92
 
77
93
  Reference **semantically related** functions only, siblings and variants that
78
- the user might reach for next:
94
+ the user might reach for next. Say why the reader would go there:
79
95
 
80
96
  ```ts
81
97
  // Good - "if partition doesn't fit, maybe filter or filterWith does"
98
+ @see {@link partitionWith} to split by a matcher
99
+ @see {@link filter} to keep only the items that pass
100
+
101
+ // Bad - no reason
82
102
  @see {@link partitionWith}
83
- @see {@link filter}
84
103
 
85
104
  // Bad - pipe is a general utility, not a related function
86
105
  @see {@link pipe}
@@ -79,7 +79,7 @@ import { partition } from "../partition.js"
79
79
  test("partition - invalid", t => {
80
80
  t.throws(
81
81
  () => {
82
- // @ts-expect-error -- testing runtime validation
82
+ // @ts-expect-error No overload matches this call
83
83
  partition(42, [1, 2])
84
84
  },
85
85
  /expected 'fn' to be 'Function' or 'Array', got 'Number'/,
@@ -88,7 +88,7 @@ test("partition - invalid", t => {
88
88
 
89
89
  t.throws(
90
90
  () => {
91
- // @ts-expect-error -- testing runtime validation
91
+ // @ts-expect-error No overload matches this call
92
92
  partition(isEven, "not-an-array")
93
93
  },
94
94
  /expected 'input' to be 'Array'/,
@@ -171,6 +171,23 @@ intentionally passes wrong types to verify runtime validation. Never use it to
171
171
  work around type inference issues — if a test needs a cast, the API needs
172
172
  fixing.
173
173
 
174
+ Follow it with the TypeScript error, in the form of the type tests: the types
175
+ and the count, `...` for the rest. The reader sees what TypeScript says before
176
+ the runtime guard throws:
177
+
178
+ ```ts
179
+ // Good
180
+ // @ts-expect-error ... type 'number' is not assignable to ... type 'string'
181
+ escapeHTML(42)
182
+
183
+ // Bad — says why the line is there, not what TypeScript reports
184
+ // @ts-expect-error -- testing runtime validation
185
+ escapeHTML(42)
186
+ ```
187
+
188
+ TSTyche checks the message in a `*.tst.ts` file only. In a tape test, `tsc`
189
+ checks that the error exists, not its text.
190
+
174
191
  ### Runtime error messages reference parameter names
175
192
 
176
193
  Error messages use quoted parameter names so it's clear which argument is wrong.
@@ -120,11 +120,11 @@ expect<{ name: string }>().type.toBeAssignableTo<PlainObject>()
120
120
  ### `@ts-expect-error` must include the error message
121
121
 
122
122
  Put `// @ts-expect-error` on the line above the call that fails, followed by the
123
- expected TypeScript error. TSTyche matches it from the start of the message, and
124
- `...` skips any part. Keep the types and the counts, they say what went wrong.
125
- Skip the words around them, eg. `Argument of` and `parameter of`. The test
126
- breaks if the error changes, and it tells the user what error to expect when
127
- they misuse the API:
123
+ expected TypeScript error. TSTyche matches it against the whole message, with
124
+ every line under it, and `...` skips any part. Keep the types and the counts,
125
+ they say what went wrong. Skip the words around them, eg. `Argument of` and
126
+ `parameter of`. The test breaks if the error changes, and it tells the user what
127
+ error to expect when they misuse the API:
128
128
 
129
129
  ```ts
130
130
  // Good — the types and the count, nothing else
@@ -138,6 +138,26 @@ write("name")
138
138
  write("name", "bob", 42)
139
139
  ```
140
140
 
141
+ TypeScript 6 and 7 can word one error differently. Keep only the types both
142
+ name, and write both messages, and what the reader should do, in a comment
143
+ above:
144
+
145
+ ```ts
146
+ // A level flattens an array. To flatten an object, pass a separator,
147
+ // eg. flatten("/")(user). TypeScript names only the types:
148
+ // TS 6: Argument of type '{ a: number; }' is not assignable to
149
+ // parameter of type 'readonly unknown[]'
150
+ // TS 7: Type '{ a: number; }' is missing the following properties
151
+ // from type 'readonly unknown[]': length, concat, join, slice,
152
+ // and 26 more
153
+ // @ts-expect-error ... '{ a: number; }' ... 'readonly unknown[]'
154
+ flatten(1)(user)
155
+ ```
156
+
157
+ When a call matches no overload, TypeScript 7 reports the error of the last
158
+ overload that takes as many arguments as the call passes. Quote that one:
159
+ TypeScript 6 lists it too.
160
+
141
161
  `toRaiseError()` is deprecated in TSTyche 7, use the directive instead. Prefer
142
162
  it over `.not.toBeCallableWith()` too: that one passes for any reason the call
143
163
  fails, eg. a missing argument.
@@ -131,6 +131,32 @@ Mark each branch with a `// @signature` comment. These comments are the currying
131
131
  contract — a reader scanning the file should immediately see all calling
132
132
  conventions without parsing the logic.
133
133
 
134
+ ### 2a. Types: one signature per arity
135
+
136
+ Give the `*Fn` type one signature per arity, eg. one uncurried and one curried.
137
+ Merge the overloads that differ only in one argument's type into a union:
138
+
139
+ ```ts
140
+ // Bad: two 3-argument overloads compete. When neither fits, TypeScript 7
141
+ // reports the last one, so `write("name", "bob", 42)` blames the path
142
+ <I, K extends string, V>(path: K, value: V, input: I): DeepWrite<I, [K], V>
143
+ <I, const P extends WritePath, V>(path: P, value: V, input: I): DeepWrite<I, P, V>
144
+
145
+ // Good: one signature, and the error names the wrong argument on TS 6 and 7
146
+ <I, const P extends string | WritePath, V>(path: P, value: V, input: I): DeepWrite<I, ToArray<P>, V>
147
+ ```
148
+
149
+ When the return type depends on an argument's type, pick it with a conditional
150
+ type, and end the cases with `never`, eg. `flatten`'s `FlattenInputFor`:
151
+
152
+ ```ts
153
+ type FlattenInputFor<LevelOrSeparator> = LevelOrSeparator extends number
154
+ ? readonly unknown[]
155
+ : LevelOrSeparator extends string
156
+ ? PlainObject
157
+ : never
158
+ ```
159
+
134
160
  ### 3. Exports
135
161
 
136
162
  Always at the end of the file:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@asd14/m",
4
- "version": "10.0.0",
4
+ "version": "11.0.0",
5
5
  "description": "Point free style, functional Javascript library with focus on object arrays",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/asd-xiv/m",
@@ -88,11 +88,11 @@
88
88
  "@asd14/prettier-config": "^1.6.0",
89
89
  "@asd14/semantic-release-config": "^2.0.0",
90
90
  "@asd14/ts-config": "^2.1.0",
91
- "@commitlint/cli": "^21.2.4",
92
- "@commitlint/config-conventional": "^21.2.4",
91
+ "@commitlint/cli": "^21.3.0",
92
+ "@commitlint/config-conventional": "^21.3.0",
93
93
  "@swc/cli": "^0.8.2",
94
94
  "@swc/core": "^1.16.22",
95
- "@types/lodash": "^4.17.27",
95
+ "@types/lodash": "^4.17.28",
96
96
  "@types/ramda": "^0.32.0",
97
97
  "@types/tape": "^5.8.1",
98
98
  "@types/underscore": "^1.13.0",
@@ -109,7 +109,7 @@
109
109
  "semantic-release": "^26.0.1",
110
110
  "tape": "^5.11.0",
111
111
  "tinybench": "^6.2.5",
112
- "tstyche": "^7.2.5",
112
+ "tstyche": "^8.0.0-beta.3",
113
113
  "tsx": "^4.23.15",
114
114
  "typescript": "^6.0.3",
115
115
  "underscore": "^1.13.8"