@forthtilliath/ts-kit 0.9.0 → 0.11.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.
- package/README.md +80 -22
- package/dist/array/createColumnStorage.d.ts +30 -0
- package/dist/array/createColumnStorage.d.ts.map +1 -0
- package/dist/array/createColumnStorage.js +51 -0
- package/dist/array/flattenDeep.d.ts +7 -5
- package/dist/array/flattenDeep.d.ts.map +1 -1
- package/dist/array/flattenDeep.js +8 -5
- package/dist/array/index.d.ts +1 -0
- package/dist/array/index.d.ts.map +1 -1
- package/dist/array/index.js +1 -0
- package/dist/async/abortReason.d.ts +9 -0
- package/dist/async/abortReason.d.ts.map +1 -0
- package/dist/async/abortReason.js +11 -0
- package/dist/async/memoize.d.ts +2 -18
- package/dist/async/memoize.d.ts.map +1 -1
- package/dist/async/memoize.js +4 -25
- package/dist/async/retry.d.ts +15 -3
- package/dist/async/retry.d.ts.map +1 -1
- package/dist/async/retry.js +15 -11
- package/dist/async/sleep.d.ts +2 -1
- package/dist/async/sleep.d.ts.map +1 -1
- package/dist/async/sleep.js +23 -2
- package/dist/async/withTimeout.d.ts +11 -4
- package/dist/async/withTimeout.d.ts.map +1 -1
- package/dist/async/withTimeout.js +31 -9
- package/dist/csv/escapeCsvField.d.ts +21 -0
- package/dist/csv/escapeCsvField.d.ts.map +1 -0
- package/dist/csv/escapeCsvField.js +28 -0
- package/dist/csv/formatCsvNumber.d.ts +14 -0
- package/dist/csv/formatCsvNumber.d.ts.map +1 -0
- package/dist/csv/formatCsvNumber.js +15 -0
- package/dist/csv/index.d.ts +2 -0
- package/dist/csv/index.d.ts.map +1 -1
- package/dist/csv/index.js +2 -0
- package/dist/date/dateInTimeZone.d.ts +22 -0
- package/dist/date/dateInTimeZone.d.ts.map +1 -0
- package/dist/date/dateInTimeZone.js +35 -0
- package/dist/date/daysUntil.d.ts +15 -0
- package/dist/date/daysUntil.d.ts.map +1 -0
- package/dist/date/daysUntil.js +22 -0
- package/dist/date/index.d.ts +3 -0
- package/dist/date/index.d.ts.map +1 -1
- package/dist/date/index.js +3 -0
- package/dist/date/todayInTimeZone.d.ts +14 -0
- package/dist/date/todayInTimeZone.d.ts.map +1 -0
- package/dist/date/todayInTimeZone.js +15 -0
- package/dist/files/downloadText.d.ts.map +1 -1
- package/dist/files/downloadText.js +9 -1
- package/dist/files/index.d.ts +1 -0
- package/dist/files/index.d.ts.map +1 -1
- package/dist/files/index.js +1 -0
- package/dist/files/sanitizeFileName.d.ts +14 -0
- package/dist/files/sanitizeFileName.d.ts.map +1 -0
- package/dist/files/sanitizeFileName.js +18 -0
- package/dist/function/index.d.ts +2 -0
- package/dist/function/index.d.ts.map +1 -0
- package/dist/function/index.js +1 -0
- package/dist/function/memoize.d.ts +34 -0
- package/dist/function/memoize.d.ts.map +1 -0
- package/dist/function/memoize.js +50 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/maths/average.d.ts +2 -7
- package/dist/maths/average.d.ts.map +1 -1
- package/dist/maths/average.js +4 -10
- package/dist/maths/sum.d.ts +2 -7
- package/dist/maths/sum.d.ts.map +1 -1
- package/dist/maths/sum.js +4 -9
- package/dist/number/average.d.ts +13 -0
- package/dist/number/average.d.ts.map +1 -0
- package/dist/number/average.js +15 -0
- package/dist/number/formatBytes.d.ts.map +1 -1
- package/dist/number/formatBytes.js +6 -2
- package/dist/number/formatCsvNumber.d.ts +2 -13
- package/dist/number/formatCsvNumber.d.ts.map +1 -1
- package/dist/number/formatCsvNumber.js +4 -15
- package/dist/number/index.d.ts +3 -0
- package/dist/number/index.d.ts.map +1 -1
- package/dist/number/index.js +3 -0
- package/dist/number/padNumber.d.ts +15 -0
- package/dist/number/padNumber.d.ts.map +1 -0
- package/dist/number/padNumber.js +16 -0
- package/dist/number/sum.d.ts +10 -0
- package/dist/number/sum.d.ts.map +1 -0
- package/dist/number/sum.js +11 -0
- package/dist/object/deepEqual.d.ts +6 -0
- package/dist/object/deepEqual.d.ts.map +1 -1
- package/dist/object/deepEqual.js +45 -11
- package/dist/string/escapeCsvField.d.ts +2 -13
- package/dist/string/escapeCsvField.d.ts.map +1 -1
- package/dist/string/escapeCsvField.js +4 -17
- package/dist/string/escapeHtml.d.ts +6 -4
- package/dist/string/escapeHtml.d.ts.map +1 -1
- package/dist/string/escapeHtml.js +8 -5
- package/dist/string/pluralize.d.ts +30 -7
- package/dist/string/pluralize.d.ts.map +1 -1
- package/dist/string/pluralize.js +48 -15
- package/dist/version/compareVersions.d.ts +8 -1
- package/dist/version/compareVersions.d.ts.map +1 -1
- package/dist/version/compareVersions.js +63 -9
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -33,10 +33,27 @@ to keep a bundle's included code obvious at a glance):
|
|
|
33
33
|
import { chunk } from "@forthtilliath/ts-kit/array/chunk";
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
### Browser-only functions
|
|
37
|
+
|
|
38
|
+
Everything runs in any JavaScript runtime (browser, Node, React Native,
|
|
39
|
+
Angular SSR…) **except** these, which need a DOM (`document`, `Image`,
|
|
40
|
+
`URL.createObjectURL`) and throw elsewhere — only call them client-side:
|
|
41
|
+
|
|
42
|
+
- `csv/downloadCsv`
|
|
43
|
+
- `files/downloadText`, `files/downloadTextBlob`
|
|
44
|
+
- `image/compressImage`
|
|
45
|
+
|
|
46
|
+
Importing them is harmless anywhere: the DOM is only touched when called.
|
|
47
|
+
|
|
36
48
|
### `array`
|
|
37
49
|
|
|
38
50
|
- `chunk(array, size)` — splits an array into chunks of a given size.
|
|
39
|
-
- `
|
|
51
|
+
- `createColumnStorage(defaults)` — `{ serialize, deserialize }` pair to
|
|
52
|
+
persist a user-customized column list (order + visibility, e.g. in
|
|
53
|
+
`localStorage`). Only `key`/`visible` are stored; on read, unknown keys are
|
|
54
|
+
dropped, new columns appended, and invalid input falls back to `defaults`.
|
|
55
|
+
- `flattenDeep(array)` — recursively flattens nested arrays, typed as the
|
|
56
|
+
innermost element type (`number[][][]` → `number[]`).
|
|
40
57
|
- `getMostRecentIds(rows, limit?)` — most recently occurring distinct ids
|
|
41
58
|
(`{ id, occurredAt }[]`), most recent first, deduplicated, limited
|
|
42
59
|
(default 5).
|
|
@@ -56,16 +73,23 @@ import { chunk } from "@forthtilliath/ts-kit/array/chunk";
|
|
|
56
73
|
|
|
57
74
|
### `async`
|
|
58
75
|
|
|
59
|
-
- `sleep(ms)` — resolves after a delay
|
|
76
|
+
- `sleep(ms, signal?)` — resolves after a delay; rejects early if `signal`
|
|
77
|
+
aborts.
|
|
60
78
|
- `retry(fn, options)` — retries an async operation with exponential backoff.
|
|
79
|
+
Options: `attempts` (3), `delayMs` (200), `backoffFactor` (2),
|
|
80
|
+
`maxDelayMs`, `shouldRetry(error, attempt)` (return `false` to rethrow at
|
|
81
|
+
once, e.g. on a 4xx), `onRetry(error, attempt)` (called before each actual
|
|
82
|
+
retry), `signal`.
|
|
61
83
|
- `debounce(fn, wait)` — delays `fn` until calls stop for `wait` ms; exposes
|
|
62
84
|
`cancel()` / `flush()`.
|
|
63
85
|
- `throttle(fn, wait)` — runs `fn` at most once per `wait` ms (leading +
|
|
64
86
|
trailing edge); exposes `cancel()`.
|
|
65
|
-
- `
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
`
|
|
87
|
+
- `withTimeout(operation, ms, message?)` — rejects with a `TimeoutError` if
|
|
88
|
+
`operation` doesn't settle in time. Pass a function `(signal) => promise`
|
|
89
|
+
instead of a promise to also **cancel** the operation on timeout (e.g.
|
|
90
|
+
`withTimeout((signal) => fetch(url, { signal }), 5000)`).
|
|
91
|
+
- `memoize` — moved to [`function`](#function); still importable from
|
|
92
|
+
`async/memoize` (deprecated).
|
|
69
93
|
|
|
70
94
|
### `classes`
|
|
71
95
|
|
|
@@ -93,11 +117,19 @@ import { chunk } from "@forthtilliath/ts-kit/array/chunk";
|
|
|
93
117
|
- `parseCsvLine(line, delimiter?)` — splits one CSV line into trimmed cells;
|
|
94
118
|
quoted cells may contain the delimiter, `""` stands for a literal quote.
|
|
95
119
|
Delimiter defaults to `","`.
|
|
96
|
-
- `toCsv(rows, delimiter?)` — serializes rows to CSV, every cell quoted
|
|
97
|
-
escaped, rows joined with `\n`.
|
|
120
|
+
- `toCsv(rows, delimiter?)` — serializes whole rows to CSV, every cell quoted
|
|
121
|
+
and escaped, rows joined with `\n`. Delimiter defaults to `","`.
|
|
122
|
+
- `escapeCsvField(value, delimiter?)` — escapes a single field (RFC 4180),
|
|
123
|
+
quoting it only if it contains a `"`, the delimiter or a line break — to
|
|
124
|
+
build rows cell by cell. Delimiter defaults to `";"` (French-locale Excel).
|
|
125
|
+
- `formatCsvNumber(value, decimals?)` — formats a number with a comma decimal
|
|
126
|
+
separator (French-locale spreadsheets) instead of JS's dot.
|
|
98
127
|
- `downloadCsv(filename, content)` — browser download as `text/csv`, with a
|
|
99
128
|
UTF-8 BOM so Excel reads accented characters.
|
|
100
129
|
|
|
130
|
+
`escapeCsvField` and `formatCsvNumber` used to live in `string/` and
|
|
131
|
+
`number/`; those deep imports still work (deprecated).
|
|
132
|
+
|
|
101
133
|
### `date`
|
|
102
134
|
|
|
103
135
|
- `startOfDay(date?)` — returns a new `Date` at local midnight.
|
|
@@ -107,13 +139,33 @@ import { chunk } from "@forthtilliath/ts-kit/array/chunk";
|
|
|
107
139
|
- `getPeriodStartMs(period, now?)` — start timestamp (ms) for a
|
|
108
140
|
`"today" | "7d" | "30d" | "all"` period filter, or `null` for `"all"`.
|
|
109
141
|
`"today"` is the current calendar day, not a rolling 24h window.
|
|
142
|
+
- `dateInTimeZone(date, timeZone)` — the calendar date of an instant in an
|
|
143
|
+
IANA time zone, `{ year, month, day, iso }` (`month` from 1 to 12), whatever
|
|
144
|
+
the machine's own time zone.
|
|
145
|
+
- `todayInTimeZone(timeZone, now?)` — today's date in that time zone: on a
|
|
146
|
+
server running in UTC, `new Date()` is still "yesterday" in Paris just
|
|
147
|
+
after midnight.
|
|
148
|
+
- `daysUntil(date, timeZone, now?)` — calendar days between today and a date,
|
|
149
|
+
both taken in that time zone (`0` today, `1` tomorrow, `-1` yesterday);
|
|
150
|
+
unaffected by the time of day or daylight saving time.
|
|
110
151
|
|
|
111
152
|
### `files`
|
|
112
153
|
|
|
113
154
|
- `downloadText(filename, text)` — triggers a browser download of a text file
|
|
114
155
|
via a `data:` URI.
|
|
115
156
|
- `downloadTextBlob(filename, text)` — same, but via a `Blob` + object URL
|
|
116
|
-
(better for larger content).
|
|
157
|
+
(better for larger content). The object URL is revoked 40 s later, not
|
|
158
|
+
right after the click (which can cancel the download in Firefox/Safari).
|
|
159
|
+
|
|
160
|
+
### `function`
|
|
161
|
+
|
|
162
|
+
- `memoize(fn, getKeyOrOptions?)` — caches `fn`'s results per argument tuple
|
|
163
|
+
(JSON-stringified by default); exposes the underlying `cache` map. Pass a
|
|
164
|
+
key function, or `{ getKey, maxSize }` to evict the least recently used
|
|
165
|
+
result beyond `maxSize`. A returned promise that rejects is evicted, so the
|
|
166
|
+
next call retries instead of failing forever.
|
|
167
|
+
- `sanitizeFileName(name)` — replaces characters forbidden in file names
|
|
168
|
+
(`\ / : * ? " < > |`) with hyphens, collapses whitespace and trims.
|
|
117
169
|
|
|
118
170
|
### `id`
|
|
119
171
|
|
|
@@ -135,19 +187,20 @@ import { chunk } from "@forthtilliath/ts-kit/array/chunk";
|
|
|
135
187
|
`bold`-aware segments), ready for a UI layer to render without a full
|
|
136
188
|
Markdown dependency.
|
|
137
189
|
|
|
138
|
-
### `maths`
|
|
139
|
-
|
|
140
|
-
- `sum(numbers)` — sum of an array of numbers.
|
|
141
|
-
- `avg(numbers)` — average of an array of numbers.
|
|
142
|
-
|
|
143
190
|
### `number`
|
|
144
191
|
|
|
192
|
+
- `sum(numbers)` — sum of an array of numbers (`0` if empty).
|
|
193
|
+
- `avg(numbers)` — average of an array of numbers; `NaN` if empty (no
|
|
194
|
+
meaningful average of nothing, like lodash's `mean`).
|
|
145
195
|
- `clamp(value, min, max)` — clamps a number between two bounds.
|
|
146
196
|
- `round(value, decimals?)` — rounds to a given number of decimal places.
|
|
147
197
|
- `formatBytes(bytes, decimals?)` — human-readable byte size ("1.5 MB").
|
|
148
198
|
- `formatDuration(ms)` — human-readable duration ("1d 1h 1m 1s").
|
|
149
|
-
- `
|
|
150
|
-
|
|
199
|
+
- `padNumber(n, total, minWidth?)` — zero-pads `n` to the width of `total`
|
|
200
|
+
(at least `minWidth`, default 2) so numbered file names sort correctly.
|
|
201
|
+
|
|
202
|
+
`sum` and `avg` used to live in `maths/`; those deep imports still work
|
|
203
|
+
(deprecated).
|
|
151
204
|
|
|
152
205
|
### `object`
|
|
153
206
|
|
|
@@ -166,15 +219,20 @@ import { chunk } from "@forthtilliath/ts-kit/array/chunk";
|
|
|
166
219
|
suffix).
|
|
167
220
|
- `slugify(str)` — URL-friendly slug (accents stripped, lower-cased,
|
|
168
221
|
hyphenated).
|
|
169
|
-
- `pluralize(count, singular, plural?)` —
|
|
170
|
-
|
|
222
|
+
- `pluralize(count, singular, plural? | { plural?, locale? })` — picks the
|
|
223
|
+
singular or the plural form. Which counts take the singular follows the
|
|
224
|
+
locale's rules (`Intl.PluralRules`, `"en"` by default): only ±1 in
|
|
225
|
+
English, 0 and 1.5 too in French. Without an explicit plural form, a naive
|
|
226
|
+
suffix: English `s`/`es`/`ies`, French `s` (nothing after `s`/`x`/`z`),
|
|
227
|
+
`s` elsewhere.
|
|
228
|
+
- `createPluralize(locale)` — `pluralize` bound to a locale, declared once per
|
|
229
|
+
app: `const plural = createPluralize("fr"); plural(n, "est", "sont")`.
|
|
171
230
|
- `normalizeForSearch(text)` — lowercases, trims, strips accents, and expands
|
|
172
231
|
œ/æ ligatures (which `normalize("NFD")` alone doesn't decompose) — for
|
|
173
232
|
accent/case-insensitive search matching.
|
|
174
|
-
- `
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
inserting user text into an HTML template.
|
|
233
|
+
- `escapeHtml(text)` — HTML entity escaping (`&`, `<`, `>`, `"`, `'`) for
|
|
234
|
+
inserting user text into an HTML template, in text content or in an
|
|
235
|
+
attribute quoted with `"` or `'`.
|
|
178
236
|
|
|
179
237
|
### `version`
|
|
180
238
|
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Minimal shape of a toggleable, reorderable column. */
|
|
2
|
+
export interface StorableColumn {
|
|
3
|
+
key: string;
|
|
4
|
+
visible: boolean;
|
|
5
|
+
}
|
|
6
|
+
export interface ColumnStorage<T extends StorableColumn> {
|
|
7
|
+
serialize: (columns: readonly T[]) => string;
|
|
8
|
+
deserialize: (raw: string) => T[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Creates a (de)serializer for a user-customized list of columns (order and
|
|
12
|
+
* visibility), e.g. to persist a table layout in `localStorage`. Only `key`
|
|
13
|
+
* and `visible` are stored; other properties (labels…) always come from
|
|
14
|
+
* `defaults`. On read, unknown keys are dropped, columns missing from the
|
|
15
|
+
* stored value are appended in their default order, and invalid JSON falls
|
|
16
|
+
* back to `defaults`.
|
|
17
|
+
*
|
|
18
|
+
* @param defaults - The default columns, in their default order.
|
|
19
|
+
* @returns A `{ serialize, deserialize }` pair.
|
|
20
|
+
* @example
|
|
21
|
+
* const storage = createColumnStorage([
|
|
22
|
+
* { key: "name", label: "Name", visible: true },
|
|
23
|
+
* { key: "email", label: "Email", visible: true },
|
|
24
|
+
* ]);
|
|
25
|
+
* storage.deserialize('[{"key":"email","visible":false}]');
|
|
26
|
+
* // => [{ key: "email", label: "Email", visible: false },
|
|
27
|
+
* // { key: "name", label: "Name", visible: true }]
|
|
28
|
+
*/
|
|
29
|
+
export declare function createColumnStorage<T extends StorableColumn>(defaults: readonly T[]): ColumnStorage<T>;
|
|
30
|
+
//# sourceMappingURL=createColumnStorage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createColumnStorage.d.ts","sourceRoot":"","sources":["../../src/array/createColumnStorage.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,cAAc;IACrD,SAAS,EAAE,CAAC,OAAO,EAAE,SAAS,CAAC,EAAE,KAAK,MAAM,CAAC;IAC7C,WAAW,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC,EAAE,CAAC;CACnC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,cAAc,EAC1D,QAAQ,EAAE,SAAS,CAAC,EAAE,GACrB,aAAa,CAAC,CAAC,CAAC,CAgClB"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a (de)serializer for a user-customized list of columns (order and
|
|
3
|
+
* visibility), e.g. to persist a table layout in `localStorage`. Only `key`
|
|
4
|
+
* and `visible` are stored; other properties (labels…) always come from
|
|
5
|
+
* `defaults`. On read, unknown keys are dropped, columns missing from the
|
|
6
|
+
* stored value are appended in their default order, and invalid JSON falls
|
|
7
|
+
* back to `defaults`.
|
|
8
|
+
*
|
|
9
|
+
* @param defaults - The default columns, in their default order.
|
|
10
|
+
* @returns A `{ serialize, deserialize }` pair.
|
|
11
|
+
* @example
|
|
12
|
+
* const storage = createColumnStorage([
|
|
13
|
+
* { key: "name", label: "Name", visible: true },
|
|
14
|
+
* { key: "email", label: "Email", visible: true },
|
|
15
|
+
* ]);
|
|
16
|
+
* storage.deserialize('[{"key":"email","visible":false}]');
|
|
17
|
+
* // => [{ key: "email", label: "Email", visible: false },
|
|
18
|
+
* // { key: "name", label: "Name", visible: true }]
|
|
19
|
+
*/
|
|
20
|
+
export function createColumnStorage(defaults) {
|
|
21
|
+
function serialize(columns) {
|
|
22
|
+
return JSON.stringify(columns.map(({ key, visible }) => ({ key, visible })));
|
|
23
|
+
}
|
|
24
|
+
function deserialize(raw) {
|
|
25
|
+
try {
|
|
26
|
+
const stored = JSON.parse(raw);
|
|
27
|
+
if (!Array.isArray(stored))
|
|
28
|
+
return [...defaults];
|
|
29
|
+
const result = [];
|
|
30
|
+
for (const entry of stored) {
|
|
31
|
+
const { key, visible } = (entry ?? {});
|
|
32
|
+
const column = defaults.find((c) => c.key === key);
|
|
33
|
+
if (!column || result.some((c) => c.key === column.key))
|
|
34
|
+
continue;
|
|
35
|
+
result.push({
|
|
36
|
+
...column,
|
|
37
|
+
visible: typeof visible === "boolean" ? visible : column.visible,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
for (const column of defaults) {
|
|
41
|
+
if (!result.some((c) => c.key === column.key))
|
|
42
|
+
result.push(column);
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return [...defaults];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return { serialize, deserialize };
|
|
51
|
+
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Recursively flattens a nested array.
|
|
2
|
+
* Recursively flattens a nested array, at any depth.
|
|
3
3
|
*
|
|
4
|
-
* @
|
|
5
|
-
* @
|
|
6
|
-
*
|
|
4
|
+
* @param array - The array to flatten (left untouched).
|
|
5
|
+
* @returns A new array with every nested element at the top level, typed as
|
|
6
|
+
* the innermost element type (`number[][][]` → `number[]`).
|
|
7
|
+
* @example
|
|
8
|
+
* flattenDeep([1, [2, [3, [4]]]]); // => [1, 2, 3, 4]
|
|
7
9
|
*/
|
|
8
|
-
export declare function flattenDeep<T>(array: T
|
|
10
|
+
export declare function flattenDeep<T extends readonly unknown[]>(array: T): FlatArray<T, 20>[];
|
|
9
11
|
//# sourceMappingURL=flattenDeep.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flattenDeep.d.ts","sourceRoot":"","sources":["../../src/array/flattenDeep.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"flattenDeep.d.ts","sourceRoot":"","sources":["../../src/array/flattenDeep.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,OAAO,EAAE,EACtD,KAAK,EAAE,CAAC,GACP,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAGpB"}
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Recursively flattens a nested array.
|
|
2
|
+
* Recursively flattens a nested array, at any depth.
|
|
3
3
|
*
|
|
4
|
-
* @
|
|
5
|
-
* @
|
|
6
|
-
*
|
|
4
|
+
* @param array - The array to flatten (left untouched).
|
|
5
|
+
* @returns A new array with every nested element at the top level, typed as
|
|
6
|
+
* the innermost element type (`number[][][]` → `number[]`).
|
|
7
|
+
* @example
|
|
8
|
+
* flattenDeep([1, [2, [3, [4]]]]); // => [1, 2, 3, 4]
|
|
7
9
|
*/
|
|
8
10
|
export function flattenDeep(array) {
|
|
9
|
-
|
|
11
|
+
// 20 is the deepest level the built-in `FlatArray` type can unwind.
|
|
12
|
+
return array.flat(Infinity);
|
|
10
13
|
}
|
package/dist/array/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/array/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/array/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,0BAA0B,CAAC;AACzC,cAAc,kBAAkB,CAAC;AACjC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,gBAAgB,CAAC"}
|
package/dist/array/index.js
CHANGED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error to reject with once `signal` is aborted: its `reason` (what was
|
|
3
|
+
* passed to `abort()`), or a standard `AbortError` when the runtime doesn't
|
|
4
|
+
* provide one (some React Native polyfills).
|
|
5
|
+
*
|
|
6
|
+
* Internal helper — not part of the package's public barrel.
|
|
7
|
+
*/
|
|
8
|
+
export declare function abortReason(signal: AbortSignal): unknown;
|
|
9
|
+
//# sourceMappingURL=abortReason.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"abortReason.d.ts","sourceRoot":"","sources":["../../src/async/abortReason.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAKxD"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error to reject with once `signal` is aborted: its `reason` (what was
|
|
3
|
+
* passed to `abort()`), or a standard `AbortError` when the runtime doesn't
|
|
4
|
+
* provide one (some React Native polyfills).
|
|
5
|
+
*
|
|
6
|
+
* Internal helper — not part of the package's public barrel.
|
|
7
|
+
*/
|
|
8
|
+
export function abortReason(signal) {
|
|
9
|
+
return (signal.reason ??
|
|
10
|
+
new DOMException("This operation was aborted", "AbortError"));
|
|
11
|
+
}
|
package/dist/async/memoize.d.ts
CHANGED
|
@@ -1,19 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/** The underlying cache, exposed for inspection or manual clearing. */
|
|
4
|
-
cache: Map<string, R>;
|
|
5
|
-
}
|
|
6
|
-
/**
|
|
7
|
-
* Caches the result of `fn` per argument tuple (JSON-stringified by
|
|
8
|
-
* default).
|
|
9
|
-
*
|
|
10
|
-
* @param fn - The function to memoize.
|
|
11
|
-
* @param getKey - Computes the cache key for a set of arguments (defaults to `JSON.stringify`).
|
|
12
|
-
* @returns A memoized version of `fn`, with a `cache` map exposed.
|
|
13
|
-
* @example
|
|
14
|
-
* const square = memoize((n: number) => expensiveSquare(n));
|
|
15
|
-
* square(4); // computed
|
|
16
|
-
* square(4); // cached
|
|
17
|
-
*/
|
|
18
|
-
export declare function memoize<Args extends unknown[], R>(fn: (...args: Args) => R, getKey?: (...args: Args) => string): MemoizedFunction<Args, R>;
|
|
1
|
+
/** @deprecated Import from `@forthtilliath/ts-kit/function/memoize` instead. */
|
|
2
|
+
export { memoize, type MemoizedFunction, type MemoizeOptions, } from "../function/memoize.js";
|
|
19
3
|
//# sourceMappingURL=memoize.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memoize.d.ts","sourceRoot":"","sources":["../../src/async/memoize.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"memoize.d.ts","sourceRoot":"","sources":["../../src/async/memoize.ts"],"names":[],"mappings":"AAGA,gFAAgF;AAChF,OAAO,EACL,OAAO,EACP,KAAK,gBAAgB,EACrB,KAAK,cAAc,GACpB,MAAM,wBAAwB,CAAC"}
|
package/dist/async/memoize.js
CHANGED
|
@@ -1,25 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
* @param fn - The function to memoize.
|
|
6
|
-
* @param getKey - Computes the cache key for a set of arguments (defaults to `JSON.stringify`).
|
|
7
|
-
* @returns A memoized version of `fn`, with a `cache` map exposed.
|
|
8
|
-
* @example
|
|
9
|
-
* const square = memoize((n: number) => expensiveSquare(n));
|
|
10
|
-
* square(4); // computed
|
|
11
|
-
* square(4); // cached
|
|
12
|
-
*/
|
|
13
|
-
export function memoize(fn, getKey = (...args) => JSON.stringify(args)) {
|
|
14
|
-
const cache = new Map();
|
|
15
|
-
const memoized = ((...args) => {
|
|
16
|
-
const key = getKey(...args);
|
|
17
|
-
if (cache.has(key))
|
|
18
|
-
return cache.get(key);
|
|
19
|
-
const result = fn(...args);
|
|
20
|
-
cache.set(key, result);
|
|
21
|
-
return result;
|
|
22
|
-
});
|
|
23
|
-
memoized.cache = cache;
|
|
24
|
-
return memoized;
|
|
25
|
-
}
|
|
1
|
+
// `memoize` isn't async-specific: it moved to `function/`. Re-exported here so
|
|
2
|
+
// the `@forthtilliath/ts-kit/async/memoize` deep import keeps working.
|
|
3
|
+
/** @deprecated Import from `@forthtilliath/ts-kit/function/memoize` instead. */
|
|
4
|
+
export { memoize, } from "../function/memoize.js";
|
package/dist/async/retry.d.ts
CHANGED
|
@@ -5,8 +5,18 @@ export interface RetryOptions {
|
|
|
5
5
|
delayMs?: number;
|
|
6
6
|
/** Backoff multiplier applied to `delayMs` after each failed attempt (default: 2). */
|
|
7
7
|
backoffFactor?: number;
|
|
8
|
-
/**
|
|
8
|
+
/** Upper bound for a single delay between two attempts (default: none). */
|
|
9
|
+
maxDelayMs?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Decides whether a failure is worth retrying — return `false` to rethrow
|
|
12
|
+
* it right away (e.g. a 4xx response that won't fix itself). Retries every
|
|
13
|
+
* error by default.
|
|
14
|
+
*/
|
|
15
|
+
shouldRetry?: (error: unknown, attempt: number) => boolean;
|
|
16
|
+
/** Called with the error and the 1-based attempt number before each retry. */
|
|
9
17
|
onRetry?: (error: unknown, attempt: number) => void;
|
|
18
|
+
/** Stops retrying (rejecting with the abort reason) once aborted. */
|
|
19
|
+
signal?: AbortSignal;
|
|
10
20
|
}
|
|
11
21
|
/**
|
|
12
22
|
* Retries an async operation with exponential backoff.
|
|
@@ -14,11 +24,13 @@ export interface RetryOptions {
|
|
|
14
24
|
* @param fn - The operation to retry. Receives the 1-based attempt number.
|
|
15
25
|
* @param options - Retry configuration.
|
|
16
26
|
* @returns The result of the first successful attempt.
|
|
17
|
-
* @throws The last error,
|
|
27
|
+
* @throws The last error once attempts are exhausted, the first error
|
|
28
|
+
* `shouldRetry` declines, or the abort reason once `signal` is aborted.
|
|
18
29
|
* @example
|
|
19
|
-
* const data = await retry(() =>
|
|
30
|
+
* const data = await retry(() => fetchJson("/api"), {
|
|
20
31
|
* attempts: 5,
|
|
21
32
|
* delayMs: 300,
|
|
33
|
+
* shouldRetry: (error) => !(error instanceof HttpError && error.status < 500),
|
|
22
34
|
* });
|
|
23
35
|
*/
|
|
24
36
|
export declare function retry<T>(fn: (attempt: number) => Promise<T>, options?: RetryOptions): Promise<T>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/async/retry.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/async/retry.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,YAAY;IAC3B,wEAAwE;IACxE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sFAAsF;IACtF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2EAA2E;IAC3E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;IAC3D,8EAA8E;IAC9E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACpD,qEAAqE;IACrE,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,KAAK,CAAC,CAAC,EAC3B,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,EACnC,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,CAAC,CAAC,CA0BZ"}
|
package/dist/async/retry.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { abortReason } from "./abortReason.js";
|
|
1
2
|
import { sleep } from "./sleep.js";
|
|
2
3
|
/**
|
|
3
4
|
* Retries an async operation with exponential backoff.
|
|
@@ -5,29 +6,32 @@ import { sleep } from "./sleep.js";
|
|
|
5
6
|
* @param fn - The operation to retry. Receives the 1-based attempt number.
|
|
6
7
|
* @param options - Retry configuration.
|
|
7
8
|
* @returns The result of the first successful attempt.
|
|
8
|
-
* @throws The last error,
|
|
9
|
+
* @throws The last error once attempts are exhausted, the first error
|
|
10
|
+
* `shouldRetry` declines, or the abort reason once `signal` is aborted.
|
|
9
11
|
* @example
|
|
10
|
-
* const data = await retry(() =>
|
|
12
|
+
* const data = await retry(() => fetchJson("/api"), {
|
|
11
13
|
* attempts: 5,
|
|
12
14
|
* delayMs: 300,
|
|
15
|
+
* shouldRetry: (error) => !(error instanceof HttpError && error.status < 500),
|
|
13
16
|
* });
|
|
14
17
|
*/
|
|
15
18
|
export async function retry(fn, options = {}) {
|
|
16
|
-
const { attempts = 3, delayMs = 200, backoffFactor = 2, onRetry } = options;
|
|
17
|
-
|
|
19
|
+
const { attempts = 3, delayMs = 200, backoffFactor = 2, maxDelayMs = Infinity, shouldRetry, onRetry, signal, } = options;
|
|
20
|
+
const maxAttempts = Math.max(1, attempts);
|
|
18
21
|
let currentDelay = delayMs;
|
|
19
|
-
for (let attempt = 1
|
|
22
|
+
for (let attempt = 1;; attempt++) {
|
|
23
|
+
if (signal?.aborted)
|
|
24
|
+
throw abortReason(signal);
|
|
20
25
|
try {
|
|
21
26
|
return await fn(attempt);
|
|
22
27
|
}
|
|
23
28
|
catch (error) {
|
|
24
|
-
|
|
29
|
+
const canRetry = attempt < maxAttempts && (shouldRetry?.(error, attempt) ?? true);
|
|
30
|
+
if (!canRetry)
|
|
31
|
+
throw error;
|
|
25
32
|
onRetry?.(error, attempt);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
currentDelay *= backoffFactor;
|
|
29
|
-
}
|
|
33
|
+
await sleep(Math.min(currentDelay, maxDelayMs), signal);
|
|
34
|
+
currentDelay *= backoffFactor;
|
|
30
35
|
}
|
|
31
36
|
}
|
|
32
|
-
throw lastError;
|
|
33
37
|
}
|
package/dist/async/sleep.d.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* Resolves after the given number of milliseconds.
|
|
3
3
|
*
|
|
4
4
|
* @param ms - The delay in milliseconds.
|
|
5
|
+
* @param signal - Rejects early (with the abort reason) when aborted.
|
|
5
6
|
* @example
|
|
6
7
|
* await sleep(1000); // waits 1 second
|
|
7
8
|
*/
|
|
8
|
-
export declare function sleep(ms: number): Promise<void>;
|
|
9
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
9
10
|
//# sourceMappingURL=sleep.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sleep.d.ts","sourceRoot":"","sources":["../../src/async/sleep.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"sleep.d.ts","sourceRoot":"","sources":["../../src/async/sleep.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAIH,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBrE"}
|
package/dist/async/sleep.js
CHANGED
|
@@ -1,10 +1,31 @@
|
|
|
1
|
+
import { abortReason } from "./abortReason.js";
|
|
1
2
|
/**
|
|
2
3
|
* Resolves after the given number of milliseconds.
|
|
3
4
|
*
|
|
4
5
|
* @param ms - The delay in milliseconds.
|
|
6
|
+
* @param signal - Rejects early (with the abort reason) when aborted.
|
|
5
7
|
* @example
|
|
6
8
|
* await sleep(1000); // waits 1 second
|
|
7
9
|
*/
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
// Rejects with the caller's own abort reason, whatever its type — like
|
|
11
|
+
// `fetch` does.
|
|
12
|
+
/* eslint-disable @typescript-eslint/prefer-promise-reject-errors */
|
|
13
|
+
export function sleep(ms, signal) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
if (signal?.aborted) {
|
|
16
|
+
reject(abortReason(signal));
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const onAbort = () => {
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
if (signal)
|
|
22
|
+
reject(abortReason(signal));
|
|
23
|
+
};
|
|
24
|
+
/* eslint-enable @typescript-eslint/prefer-promise-reject-errors */
|
|
25
|
+
const timer = setTimeout(() => {
|
|
26
|
+
signal?.removeEventListener("abort", onAbort);
|
|
27
|
+
resolve();
|
|
28
|
+
}, ms);
|
|
29
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
30
|
+
});
|
|
10
31
|
}
|
|
@@ -6,14 +6,21 @@ export declare class TimeoutError extends Error {
|
|
|
6
6
|
constructor(message?: string);
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
|
-
* Rejects with a {@link TimeoutError} if `
|
|
9
|
+
* Rejects with a {@link TimeoutError} if `operation` has not settled within
|
|
10
10
|
* `ms` milliseconds.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
12
|
+
* Pass a function rather than a promise to also **cancel** the operation on
|
|
13
|
+
* timeout: it receives an `AbortSignal`, aborted (with the `TimeoutError`)
|
|
14
|
+
* when time runs out — hand it to `fetch` or any abortable API. A plain
|
|
15
|
+
* promise can only be given up on, not stopped.
|
|
16
|
+
*
|
|
17
|
+
* @param operation - The promise to race against the timeout, or a function
|
|
18
|
+
* starting the operation with the given `AbortSignal`.
|
|
13
19
|
* @param ms - The timeout in milliseconds.
|
|
14
20
|
* @param message - Optional error message (defaults to a generic one).
|
|
15
21
|
* @example
|
|
16
|
-
* await withTimeout(fetch("/api"), 5000);
|
|
22
|
+
* await withTimeout((signal) => fetch("/api", { signal }), 5000); // aborted on timeout
|
|
23
|
+
* await withTimeout(somePromise, 5000); // only stops waiting
|
|
17
24
|
*/
|
|
18
|
-
export declare function withTimeout<T>(
|
|
25
|
+
export declare function withTimeout<T>(operation: Promise<T> | ((signal: AbortSignal) => Promise<T>), ms: number, message?: string): Promise<T>;
|
|
19
26
|
//# sourceMappingURL=withTimeout.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withTimeout.d.ts","sourceRoot":"","sources":["../../src/async/withTimeout.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,SAAwB;CAI5C;AAED
|
|
1
|
+
{"version":3,"file":"withTimeout.d.ts","sourceRoot":"","sources":["../../src/async/withTimeout.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,SAAwB;CAI5C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,EAC7D,EAAE,EAAE,MAAM,EACV,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,CAAC,CAAC,CA2BZ"}
|