@asd14/m 9.1.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.
Files changed (54) hide show
  1. package/dist/src/debounce/debounce.d.ts +13 -1
  2. package/dist/src/debounce/debounce.js +27 -20
  3. package/dist/src/distinct/by/distinct-by.d.ts +3 -0
  4. package/dist/src/distinct/by/distinct-by.js +3 -0
  5. package/dist/src/distinct/distinct.js +12 -3
  6. package/dist/src/escape/escape.js +6 -1
  7. package/dist/src/escape/html/escape-html.d.ts +17 -2
  8. package/dist/src/escape/html/escape-html.js +17 -2
  9. package/dist/src/escape/reg-exp/escape-reg-exp.d.ts +3 -2
  10. package/dist/src/escape/reg-exp/escape-reg-exp.js +11 -4
  11. package/dist/src/flatten/flatten.d.ts +38 -26
  12. package/dist/src/flatten/flatten.js +94 -36
  13. package/dist/src/fuzzy-match/fuzzy-match.d.ts +3 -0
  14. package/dist/src/fuzzy-match/fuzzy-match.js +91 -55
  15. package/dist/src/group/group-by.d.ts +3 -0
  16. package/dist/src/group/group-by.js +10 -1
  17. package/dist/src/index-by/index-by.d.ts +3 -0
  18. package/dist/src/index-by/index-by.js +10 -1
  19. package/dist/src/index.d.ts +0 -1
  20. package/dist/src/index.js +0 -1
  21. package/dist/src/intersect/by/intersect-by.d.ts +3 -0
  22. package/dist/src/intersect/by/intersect-by.js +3 -0
  23. package/dist/src/is-deep-equal/is-deep-equal.d.ts +20 -5
  24. package/dist/src/is-deep-equal/is-deep-equal.js +44 -7
  25. package/dist/src/is-match/is-match.d.ts +4 -0
  26. package/dist/src/is-match/is-match.js +4 -0
  27. package/dist/src/is-uri/is-uri.js +12 -9
  28. package/dist/src/merge/merge.d.ts +5 -1
  29. package/dist/src/merge/merge.js +12 -6
  30. package/dist/src/pick/pick.js +7 -0
  31. package/dist/src/throttle/throttle.d.ts +11 -1
  32. package/dist/src/throttle/throttle.js +49 -43
  33. package/dist/src/unite/by/unite-by.d.ts +3 -0
  34. package/dist/src/unite/by/unite-by.js +3 -0
  35. package/dist/src/update/update.d.ts +2 -2
  36. package/dist/src/utils/build-patch.js +3 -1
  37. package/dist/src/utils/parse-timer-options.d.ts +22 -0
  38. package/dist/src/utils/parse-timer-options.js +44 -0
  39. package/dist/src/utils/set-own.d.ts +5 -4
  40. package/dist/src/utils/set-own.js +6 -5
  41. package/dist/src/write/write.d.ts +3 -4
  42. package/dist/src/zip-to-object/zip-to-object.js +7 -0
  43. package/dist/types/array.d.ts +12 -0
  44. package/dist/types/object.d.ts +8 -4
  45. package/dist/types/object.matcher.d.ts +4 -2
  46. package/docs/SPEC.md +11 -11
  47. package/docs/how-to/jsdoc.md +33 -14
  48. package/docs/how-to/prototype-pollution-tests.md +156 -0
  49. package/docs/how-to/tape-runtime-tests.md +49 -23
  50. package/docs/how-to/tstyche-type-tests.md +49 -14
  51. package/docs/how-to/writing-functions.md +26 -0
  52. package/package.json +10 -7
  53. package/dist/src/evolve/deep-by/evolve-deep-by.d.ts +0 -65
  54. package/dist/src/evolve/deep-by/evolve-deep-by.js +0 -90
@@ -1,25 +1,41 @@
1
- import { isPlainObject } from "../is/is.js";
2
1
  import { type } from "../type/type.js";
3
- const _throttle = (fn, wait, hasLastCall)=>{
4
- let lastExecution = Date.now() - wait;
5
- let timer;
2
+ import { _parseTimerOptions } from "../utils/parse-timer-options.js";
3
+ const _throttle = (fn, wait, hasLastCall, signal)=>{
4
+ // The window opens when fn runs, and closes when its timer fires. No clock
5
+ // is read, so a wall clock that steps back cannot stretch the window
6
+ let windowTimer;
7
+ // The last call the window dropped, run when the window closes
8
+ let lastParams;
9
+ const run = (params)=>{
10
+ fn(...params);
11
+ // With no wait, every call runs: a 0 ms window would still drop the
12
+ // calls made before the next task
13
+ if (wait > 0) {
14
+ windowTimer = setTimeout(()=>{
15
+ windowTimer = undefined;
16
+ if (lastParams) {
17
+ const params = lastParams;
18
+ lastParams = undefined;
19
+ run(params);
20
+ }
21
+ }, wait);
22
+ }
23
+ };
24
+ signal?.addEventListener("abort", ()=>{
25
+ clearTimeout(windowTimer);
26
+ windowTimer = undefined;
27
+ lastParams = undefined;
28
+ }, {
29
+ once: true
30
+ });
6
31
  return (...params)=>{
7
- const now = Date.now();
8
- if (lastExecution + wait <= now) {
9
- clearTimeout(timer);
10
- timer = undefined;
11
- lastExecution = now;
12
- fn(...params);
32
+ if (signal?.aborted) {
13
33
  return;
14
34
  }
15
- // The window dropped this call: run it at the end of the window
16
- if (hasLastCall) {
17
- clearTimeout(timer);
18
- timer = setTimeout(()=>{
19
- timer = undefined;
20
- lastExecution = Date.now();
21
- fn(...params);
22
- }, lastExecution + wait - now);
35
+ if (windowTimer === undefined) {
36
+ run(params);
37
+ } else if (hasLastCall) {
38
+ lastParams = params;
23
39
  }
24
40
  };
25
41
  };
@@ -51,40 +67,30 @@ const _throttle = (fn, wait, hasLastCall)=>{
51
67
  * onScroll(2)
52
68
  * // update(1) runs now, update(2) runs 100 ms later
53
69
  *
70
+ * // Abort with a signal: the call waiting for the window end never runs, and
71
+ * // later calls do nothing. The same signal removes the listener
72
+ * const controller = new AbortController()
73
+ * const onResize = throttle({ wait: 100, signal: controller.signal }, layout)
74
+ *
75
+ * window.addEventListener("resize", onResize, { signal: controller.signal })
76
+ * controller.abort()
77
+ *
54
78
  * @name throttle
55
79
  * @tag Function
56
80
  *
57
81
  * @see {@link debounce}
58
82
  */ const throttle = (...params)=>{
59
83
  const fn = params[params.length - 1];
60
- let wait = 50;
61
- let hasLastCall = false;
62
- if (params.length > 1) {
63
- const options = params[0];
64
- if (!isPlainObject(options)) {
65
- throw new TypeError(`@asd14/m/throttle: expected 'options' to be 'Object', got '${type(options)}'`);
66
- }
67
- const optionWait = options["wait"];
68
- const optionHasLastCall = options["hasLastCall"];
69
- if (optionWait !== undefined) {
70
- if (typeof optionWait !== "number") {
71
- throw new TypeError(`@asd14/m/throttle: expected 'wait' to be 'Number', got '${type(optionWait)}'`);
72
- }
73
- if (!(optionWait >= 0)) {
74
- throw new TypeError(`@asd14/m/throttle: expected 'wait' to be 'NonNegative', got '${String(optionWait)}'`);
75
- }
76
- wait = optionWait;
77
- }
78
- if (optionHasLastCall !== undefined) {
79
- if (typeof optionHasLastCall !== "boolean") {
80
- throw new TypeError(`@asd14/m/throttle: expected 'hasLastCall' to be 'Boolean', got '${type(optionHasLastCall)}'`);
81
- }
82
- hasLastCall = optionHasLastCall;
83
- }
84
+ const { options, wait, signal } = _parseTimerOptions(params.length > 1 ? params[0] : undefined, {
85
+ fnName: "throttle"
86
+ });
87
+ const { hasLastCall = false } = options;
88
+ if (typeof hasLastCall !== "boolean") {
89
+ throw new TypeError(`@asd14/m/throttle: expected 'hasLastCall' to be 'Boolean', got '${type(hasLastCall)}'`);
84
90
  }
85
91
  if (typeof fn !== "function") {
86
92
  throw new TypeError(`@asd14/m/throttle: expected 'fn' to be 'Function', got '${type(fn)}'`);
87
93
  }
88
- return _throttle(fn, wait, hasLastCall);
94
+ return _throttle(fn, wait, hasLastCall, signal);
89
95
  };
90
96
  export { throttle };
@@ -8,6 +8,9 @@ type UniteByFn = {
8
8
  * array of the items of both arrays, where the first of each group of equal
9
9
  * items wins. Order is preserved - items from the first array appear first.
10
10
  *
11
+ * Compares each item with each kept item, so the time grows with the square
12
+ * of the input. To compare with SameValueZero, use `unite`, which is linear.
13
+ *
11
14
  * Input is never mutated - always returns a new array.
12
15
  *
13
16
  * @param {Function} fn - `(newItem, keptItem) => boolean`, true when equal
@@ -15,6 +15,9 @@ const _uniteBy = (fn, a, b)=>{
15
15
  * array of the items of both arrays, where the first of each group of equal
16
16
  * items wins. Order is preserved - items from the first array appear first.
17
17
  *
18
+ * Compares each item with each kept item, so the time grows with the square
19
+ * of the input. To compare with SameValueZero, use `unite`, which is linear.
20
+ *
18
21
  * Input is never mutated - always returns a new array.
19
22
  *
20
23
  * @param {Function} fn - `(newItem, keptItem) => boolean`, true when equal
@@ -1,5 +1,5 @@
1
- import type { PlainObject } from "../../types/object.js";
2
- import type { Patcher } from "../../types/object.patcher.js";
1
+ import type { Patcher } from "../../types/object.patcher.ts";
2
+ import type { PlainObject } from "../../types/object.ts";
3
3
  type UpdateFn = {
4
4
  <T extends PlainObject>(patcher: Patcher<T>, input: T): T;
5
5
  <T extends PlainObject>(patcher: Patcher<T>): <U extends T>(input: U) => U;
@@ -51,7 +51,9 @@ import { type } from "../type/type.js";
51
51
  if (isTransformOnly && !Object.hasOwn(input, key)) {
52
52
  continue;
53
53
  }
54
- _setOwn(result, key, isFunction ? value(input[key], input) : value);
54
+ _setOwn(result, key, // An own value only: a key the input lacks, eg. toString, gives
55
+ // undefined, not the value Object.prototype has
56
+ isFunction ? value(Object.hasOwn(input, key) ? input[key] : undefined, input) : value);
55
57
  }
56
58
  return result;
57
59
  };
@@ -0,0 +1,22 @@
1
+ import type { PlainObject } from "../../types/object.js";
2
+ type TimerOptions = {
3
+ /** The options object, checked to be plain, for the options of one caller */
4
+ options: PlainObject;
5
+ wait: number;
6
+ signal: AbortSignal | undefined;
7
+ };
8
+ /**
9
+ * Check the options that `debounce` and `throttle` share: `wait`, a delay a
10
+ * timer can hold, and `signal`, an `AbortSignal`.
11
+ *
12
+ * @example
13
+ * _parseTimerOptions({ wait: 300 }, { fnName: "debounce" })
14
+ * // => { options: { wait: 300 }, wait: 300, signal: undefined }
15
+ *
16
+ * _parseTimerOptions({ wait: Infinity }, { fnName: "debounce" })
17
+ * // throws "@asd14/m/debounce: expected 'wait' to be 'TimerDelay', got 'Infinity'"
18
+ */
19
+ declare const _parseTimerOptions: (options: unknown, { fnName }: {
20
+ fnName: string;
21
+ }) => TimerOptions;
22
+ export { _parseTimerOptions };
@@ -0,0 +1,44 @@
1
+ import { isPlainObject } from "../is/is.js";
2
+ import { type } from "../type/type.js";
3
+ // A timer stores its delay in 32 bits. Node and browsers run a larger delay,
4
+ // or Infinity, after 1 ms
5
+ const MAX_TIMER_DELAY = 2_147_483_647;
6
+ const DEFAULT_WAIT = 50;
7
+ /**
8
+ * Check the options that `debounce` and `throttle` share: `wait`, a delay a
9
+ * timer can hold, and `signal`, an `AbortSignal`.
10
+ *
11
+ * @example
12
+ * _parseTimerOptions({ wait: 300 }, { fnName: "debounce" })
13
+ * // => { options: { wait: 300 }, wait: 300, signal: undefined }
14
+ *
15
+ * _parseTimerOptions({ wait: Infinity }, { fnName: "debounce" })
16
+ * // throws "@asd14/m/debounce: expected 'wait' to be 'TimerDelay', got 'Infinity'"
17
+ */ const _parseTimerOptions = (options, { fnName })=>{
18
+ if (options === undefined) {
19
+ return {
20
+ options: {},
21
+ wait: DEFAULT_WAIT,
22
+ signal: undefined
23
+ };
24
+ }
25
+ if (!isPlainObject(options)) {
26
+ throw new TypeError(`@asd14/m/${fnName}: expected 'options' to be 'Object', got '${type(options)}'`);
27
+ }
28
+ const { wait = DEFAULT_WAIT, signal } = options;
29
+ if (typeof wait !== "number") {
30
+ throw new TypeError(`@asd14/m/${fnName}: expected 'wait' to be 'Number', got '${type(wait)}'`);
31
+ }
32
+ if (!(wait >= 0 && wait <= MAX_TIMER_DELAY)) {
33
+ throw new TypeError(`@asd14/m/${fnName}: expected 'wait' to be 'TimerDelay', got '${String(wait)}'`);
34
+ }
35
+ if (signal !== undefined && !(signal instanceof AbortSignal)) {
36
+ throw new TypeError(`@asd14/m/${fnName}: expected 'signal' to be 'AbortSignal', got '${type(signal)}'`);
37
+ }
38
+ return {
39
+ options,
40
+ wait,
41
+ signal
42
+ };
43
+ };
44
+ export { _parseTimerOptions };
@@ -2,10 +2,11 @@ import type { PlainObject } from "../../types/object.js";
2
2
  /**
3
3
  * Set an own key on an object that the caller is building.
4
4
  *
5
- * A plain assignment of `__proto__` calls the setter of `Object.prototype` and
6
- * changes the prototype in place of setting a key. `__proto__` is the one
7
- * accessor on `Object.prototype`, so every other key keeps the assignment,
8
- * which builds an object about 11 times faster than `Object.defineProperty`.
5
+ * A plain assignment of a key that the prototype chain has, eg. `__proto__` or
6
+ * `constructor`, reaches the inherited property: it calls the `__proto__`
7
+ * setter, and it throws when the prototype is frozen. Such a key gets
8
+ * `Object.defineProperty`. Every other key keeps the assignment, which builds
9
+ * an object about 11 times faster.
9
10
  *
10
11
  * Writes into `target`. Pass only an object you created.
11
12
  *
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Set an own key on an object that the caller is building.
3
3
  *
4
- * A plain assignment of `__proto__` calls the setter of `Object.prototype` and
5
- * changes the prototype in place of setting a key. `__proto__` is the one
6
- * accessor on `Object.prototype`, so every other key keeps the assignment,
7
- * which builds an object about 11 times faster than `Object.defineProperty`.
4
+ * A plain assignment of a key that the prototype chain has, eg. `__proto__` or
5
+ * `constructor`, reaches the inherited property: it calls the `__proto__`
6
+ * setter, and it throws when the prototype is frozen. Such a key gets
7
+ * `Object.defineProperty`. Every other key keeps the assignment, which builds
8
+ * an object about 11 times faster.
8
9
  *
9
10
  * Writes into `target`. Pass only an object you created.
10
11
  *
@@ -15,7 +16,7 @@
15
16
  * Object.keys(result)
16
17
  * // => ["__proto__"]
17
18
  */ const _setOwn = (target, key, value)=>{
18
- if (key === "__proto__") {
19
+ if (key in target && !Object.hasOwn(target, key)) {
19
20
  Object.defineProperty(target, key, {
20
21
  value,
21
22
  enumerable: true,
@@ -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
@@ -48,6 +48,13 @@ const _zipToObject = (keys, values)=>{
48
48
  if (!Array.isArray(keys)) {
49
49
  throw new TypeError(`@asd14/m/zipToObject: expected 'keys' to be 'Array', got '${type(keys)}'`);
50
50
  }
51
+ // A key that is not a string passes the check of _setOwn, then the
52
+ // assignment turns it into one, eg. ["__proto__"] into "__proto__"
53
+ for(let i = 0, length = keys.length; i < length; i++){
54
+ if (typeof keys[i] !== "string") {
55
+ throw new TypeError(`@asd14/m/zipToObject: expected 'keys[${i}]' to be 'String', got '${type(keys[i])}'`);
56
+ }
57
+ }
51
58
  // @signature (keys) => (values)
52
59
  if (params.length === 1) {
53
60
  return (values)=>_zipToObject(keys, values);
@@ -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];
@@ -100,16 +100,20 @@ export type DeepWrite<T, Path extends readonly Property[], V> = Path extends rea
100
100
  [K in keyof O]: O[K];
101
101
  } : never : unknown;
102
102
  /**
103
- * Resolve the type of all values of an object (union)
103
+ * Resolve the type of all leaf values of an object (union). An array is not a
104
+ * leaf: its items are. A recursive type, eg. a tree, stops after 10 levels,
105
+ * which loses no leaf type, since each level adds the same ones
104
106
  *
105
107
  * @example
106
108
  * DeepValues<{ a: number, b: string }>
107
109
  * // => number | string
108
110
  *
109
111
  * DeepValues<{ a: number, b: { c: string[] } }>
110
- * // => number | string[]
112
+ * // => number | string
111
113
  */
112
- export type DeepValues<T extends PlainObject> = {
113
- [K in keyof T]: T[K] extends PlainObject ? DeepValues<T[K]> : T[K];
114
+ export type DeepValues<T extends PlainObject, Depth extends unknown[] = []> = Depth["length"] extends 10 ? never : {
115
+ [K in keyof T]: T[K] extends infer Value ? Value extends readonly unknown[] ? DeepValues<{
116
+ item: Value[number];
117
+ }, [...Depth, unknown]> : Value extends PlainObject ? DeepValues<Value, [...Depth, unknown]> : Value : never;
114
118
  }[keyof T];
115
119
  export {};
@@ -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
  })
@@ -106,12 +106,12 @@ update({ tags: () => [] }, todo)
106
106
 
107
107
  Each concept follows the same rule in every function:
108
108
 
109
- | Concept | Rule |
110
- | -------------------- | ----------------------------------------------------------- |
111
- | A predicate passes | when it returns `=== true` |
112
- | Two values are equal | SameValueZero, as `Array.prototype.includes` |
113
- | A key | an own key, read with `Object.hasOwn` |
114
- | An object | a plain object: its prototype is `Object.prototype` or null |
109
+ | Concept | Rule |
110
+ | -------------------- | ----------------------------------------------------------------------------------- |
111
+ | A predicate passes | when it returns `=== true` |
112
+ | Two values are equal | SameValueZero, as `Array.prototype.includes` |
113
+ | A key | an own key, read with `Object.hasOwn`, `__proto__` too. The prototype never changes |
114
+ | An object | a plain object: its prototype is `Object.prototype` or null |
115
115
 
116
116
  ```ts
117
117
  // Bad: remove compares with `===`, while distinct uses SameValueZero
@@ -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}
@@ -0,0 +1,156 @@
1
+ # Prototype pollution tests
2
+
3
+ Tests are the primary way users learn how a function works. For a function that
4
+ writes keys from input, eg. `write`, `merge` or `groupBy`, they also show the
5
+ one thing a user cannot see from a call: what happens when the input comes from
6
+ an attacker. A request body can carry a key named `__proto__`, and an assignment
7
+ of that key replaces the prototype of the object it lands on.
8
+
9
+ m gives such a key no special meaning: `__proto__` and `constructor` are
10
+ ordinary own keys, and the prototype never changes. A test of a function that
11
+ writes keys shows that, for each payload below. The reader should walk away
12
+ knowing:
13
+
14
+ - **Which payloads reach a prototype** — and that the function stops each one
15
+ - **What the function returns instead** — an own key they can read back, or an
16
+ error that names the bad part
17
+
18
+ ## The payloads
19
+
20
+ | Payload | Reaches the prototype through |
21
+ | :-------------------------------------- | :----------------------------------------------- |
22
+ | `JSON.parse('{"__proto__": {"x": 1}}')` | an own `__proto__` key, assigned to the result |
23
+ | `"__proto__.x"`, `["__proto__", "x"]` | a path segment |
24
+ | `["constructor", "prototype", "x"]` | the constructor's prototype |
25
+ | `[["__proto__"]]`, a key in an array | a key that is not a string, coerced at the write |
26
+ | `"constructor"`, prototype frozen | an assignment to a read-only inherited key |
27
+
28
+ Test each payload the function can receive: a path payload for `write` and
29
+ `unflatten`, a key payload for `zipToObject` and `pick`, a JSON payload for
30
+ every function that copies the keys of an object.
31
+
32
+ ## Full example
33
+
34
+ ```ts
35
+ // write.test.ts
36
+ import test from "tape"
37
+
38
+ import { write } from "./write.js"
39
+ import { read } from "../read/read.js"
40
+
41
+ test("write - prototype pollution", t => {
42
+ {
43
+ const result = write(["__proto__", "x"], 1, {})
44
+
45
+ t.deepEqual(
46
+ Object.keys(result),
47
+ ["__proto__"],
48
+ "given [a __proto__ segment] should [write an own key]"
49
+ )
50
+ t.equal(
51
+ Object.getPrototypeOf(result),
52
+ Object.prototype,
53
+ "given [a __proto__ segment] should [keep the prototype]"
54
+ )
55
+ t.equal(
56
+ "x" in {},
57
+ false,
58
+ "given [a __proto__ segment] should [not pollute other objects]"
59
+ )
60
+ }
61
+
62
+ {
63
+ const result = write("constructor", 2, {})
64
+
65
+ t.equal(
66
+ result.constructor,
67
+ 2,
68
+ "given [the key constructor] should [read back the written value with a dot]"
69
+ )
70
+ t.equal(
71
+ read("constructor")(result),
72
+ 2,
73
+ "given [the key constructor] should [read back the written value with read]"
74
+ )
75
+ }
76
+
77
+ t.end()
78
+ })
79
+ ```
80
+
81
+ ## Rules
82
+
83
+ ### Assert four facts per payload
84
+
85
+ | Fact | Assert |
86
+ | :---------------------- | :----------------------------------------------------- |
87
+ | the key is an own key | `Object.keys(result)`, or `Object.hasOwn(result, key)` |
88
+ | it reads back | with a dot, with brackets and with `read` |
89
+ | the prototype stays | `Object.getPrototypeOf(result) === Object.prototype` |
90
+ | no other object changed | a fresh `{}` lacks the payload's key, eg. `"x" in {}` |
91
+
92
+ One fact alone misses a case. A result with a replaced prototype still reads
93
+ `result.x` as `1`, so only the prototype check catches it.
94
+
95
+ ### Expose before you fix
96
+
97
+ Run a new test against the code before the fix, and see it fail. A test that
98
+ passes on both sides proves nothing: an assignment to `constructor` already
99
+ creates an own key while `Object.prototype` is writable, so that test exposes a
100
+ bug only with a frozen prototype.
101
+
102
+ ### A frozen prototype gets its own file
103
+
104
+ `Object.freeze(Object.prototype)` reaches every test that runs after it in the
105
+ same process. `node --test` runs each file in its own process, so put the freeze
106
+ in a file of its own, next to the function:
107
+
108
+ ```ts
109
+ // set-own.frozen-prototype.test.ts
110
+ import test from "tape"
111
+
112
+ import { _setOwn } from "./set-own.js"
113
+ import type { PlainObject } from "../../types/object.js"
114
+
115
+ // An app can freeze Object.prototype to stop pollution. An assignment to a key
116
+ // the prototype has, eg. `constructor`, then throws. This file runs in its own
117
+ // process, so the freeze reaches no other test
118
+ Object.freeze(Object.prototype)
119
+
120
+ test("_setOwn - frozen Object.prototype", t => {
121
+ const result: PlainObject = {}
122
+
123
+ _setOwn(result, "constructor", "admin")
124
+
125
+ t.deepEqual(
126
+ result,
127
+ { constructor: "admin" },
128
+ "given [a key of a frozen Object.prototype] should [set an own key, not throw]"
129
+ )
130
+
131
+ t.end()
132
+ })
133
+ ```
134
+
135
+ ### Write keys with `_setOwn`, never `Object.assign`
136
+
137
+ `Object.assign` and a `for…in` loop that assigns each key reach the `__proto__`
138
+ setter, so an own `__proto__` key from `JSON.parse` replaces the prototype of
139
+ the target. A spread, `{ ...object }`, and `Object.fromEntries` define keys
140
+ instead, and so does `_setOwn`, which every function of m writes through:
141
+
142
+ ```ts
143
+ const body = JSON.parse('{"__proto__": {"isAdmin": true}}')
144
+
145
+ Object.assign({}, body).isAdmin
146
+ // => true: the copy's prototype is the attacker's object
147
+
148
+ merge({}, body).isAdmin
149
+ // => undefined: `merge` writes through _setOwn, so "__proto__" is an own key
150
+ ```
151
+
152
+ ### Build the result through the function, never by hand
153
+
154
+ Test the object the function returns. An object built with `Object.create` or a
155
+ cast, eg. `Object.create(frozen) as PlainObject`, is one m never writes into, so
156
+ its test proves nothing about m.