@common.js/p-memoize 7.1.1 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,4 +2,4 @@
2
2
 
3
3
  The [p-memoize](https://www.npmjs.com/package/p-memoize) package exported as CommonJS modules.
4
4
 
5
- Exported from [p-memoize@7.1.1](https://www.npmjs.com/package/p-memoize/v/7.1.1) using https://github.com/etienne-martin/common.js.
5
+ Exported from [p-memoize@8.0.0](https://www.npmjs.com/package/p-memoize/v/8.0.0) using https://github.com/etienne-martin/common.js.
package/dist/index.d.ts CHANGED
@@ -1,15 +1,22 @@
1
1
  import type { AsyncReturnType } from 'type-fest';
2
- export declare type AnyAsyncFunction = (...arguments_: readonly any[]) => Promise<unknown | void>;
3
- export declare type CacheStorage<KeyType, ValueType> = {
2
+ export type AnyAsyncFunction = (...arguments_: readonly any[]) => Promise<unknown | void>;
3
+ export type CacheStorage<KeyType, ValueType> = {
4
4
  has: (key: KeyType) => Promise<boolean> | boolean;
5
5
  get: (key: KeyType) => Promise<ValueType | undefined> | ValueType | undefined;
6
6
  set: (key: KeyType, value: ValueType) => Promise<unknown> | unknown;
7
7
  delete: (key: KeyType) => unknown;
8
8
  clear?: () => unknown;
9
9
  };
10
- export declare type Options<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType> = {
10
+ /**
11
+ Controls whether a fulfilled value should be written to the cache.
12
+ */
13
+ export type ShouldCache<KeyType, ValueType, ArgumentsList extends readonly unknown[] = readonly unknown[]> = (value: ValueType, context: {
14
+ key: KeyType;
15
+ argumentsList: ArgumentsList;
16
+ }) => boolean | Promise<boolean>;
17
+ export type Options<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType> = {
11
18
  /**
12
- Determines the cache key for storing the result based on the function arguments. By default, __only the first argument is considered__ and it only works with [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
19
+ Determines the cache key for storing the result based on the function arguments. By default, __only the first argument is considered__ and it only works with [primitives](https://developer.mozilla.org/docs/Glossary/Primitive).
13
20
 
14
21
  A `cacheKey` function can return any type supported by `Map` (or whatever structure you use in the `cache` option).
15
22
 
@@ -41,6 +48,33 @@ export declare type Options<FunctionToMemoize extends AnyAsyncFunction, CacheKey
41
48
  @example new WeakMap()
42
49
  */
43
50
  readonly cache?: CacheStorage<CacheKeyType, AsyncReturnType<FunctionToMemoize>> | false;
51
+ /**
52
+ Controls whether a fulfilled value should be written to the cache.
53
+
54
+ It runs after the function fulfills and before `cache.set`.
55
+
56
+ - Omit to keep current behavior (always write).
57
+ - Return `false` to skip writing to the cache (in-flight de-duplication is still cleared).
58
+ - Throw or reject to propagate the error and skip caching.
59
+
60
+ @example
61
+ ```
62
+ import pMemoize from 'p-memoize';
63
+
64
+ // Only cache defined values
65
+ const getMaybe = pMemoize(async key => db.get(key), {
66
+ shouldCache: value => value !== undefined,
67
+ });
68
+
69
+ // Only cache non-empty arrays
70
+ const search = pMemoize(async query => fetchResults(query), {
71
+ shouldCache: value => Array.isArray(value) && value.length > 0,
72
+ });
73
+ ```
74
+
75
+ Note: This only affects writes; reads from the cache are unchanged.
76
+ */
77
+ readonly shouldCache?: ShouldCache<CacheKeyType, AsyncReturnType<FunctionToMemoize>, Parameters<FunctionToMemoize>>;
44
78
  };
45
79
  /**
46
80
  [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.
@@ -66,13 +100,14 @@ await delay(2000);
66
100
  await memoizedGot('https://sindresorhus.com');
67
101
  ```
68
102
  */
69
- export default function pMemoize<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType>(fn: FunctionToMemoize, { cacheKey, cache, }?: Options<FunctionToMemoize, CacheKeyType>): FunctionToMemoize;
103
+ export default function pMemoize<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType = Parameters<FunctionToMemoize>[0], OptionsType = Options<FunctionToMemoize, CacheKeyType>>(fn: FunctionToMemoize, options?: OptionsType & Options<FunctionToMemoize, CacheKeyType>): FunctionToMemoize;
70
104
  /**
71
- - Only class methods and getters/setters can be memoized, not regular functions (they aren't part of the proposal);
72
- - Only [TypeScript’s decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators) are supported, not [Babel’s](https://babeljs.io/docs/en/babel-plugin-proposal-decorators), which use a different version of the proposal;
73
- - Being an experimental feature, they need to be enabled with `--experimentalDecorators`; follow TypeScript’s docs.
105
+ - Only class methods are supported; regular functions are not part of the decorators proposals.
106
+ - Uses the new ECMAScript decorators (TypeScript 5.0+). Legacy `experimentalDecorators` are not supported.
107
+ - Babel’s legacy decorators are not supported.
108
+ - Private methods are not supported.
74
109
 
75
- @returns A [decorator](https://github.com/tc39/proposal-decorators) to memoize class methods or static class methods.
110
+ @returns A decorator to memoize class methods or static class methods.
76
111
 
77
112
  @example
78
113
  ```
@@ -97,7 +132,7 @@ class ExampleWithOptions {
97
132
  }
98
133
  ```
99
134
  */
100
- export declare function pMemoizeDecorator<FunctionToMemoize extends AnyAsyncFunction, CacheKeyType>(options?: Options<FunctionToMemoize, CacheKeyType>): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
135
+ export declare function pMemoizeDecorator<FunctionToMemoize extends AnyAsyncFunction = AnyAsyncFunction, CacheKeyType = Parameters<FunctionToMemoize>[0]>(options?: Options<NoInfer<FunctionToMemoize>, NoInfer<CacheKeyType>>): <This, Value extends FunctionToMemoize>(value: Value, context: ClassMethodDecoratorContext<This, Value>) => void;
101
136
  /**
102
137
  Clear all cached data of a memoized function.
103
138
 
package/dist/index.js CHANGED
@@ -42,7 +42,7 @@ await memoizedGot('https://sindresorhus.com');
42
42
  return pMemoizeClear;
43
43
  }
44
44
  });
45
- var _mimicFn = /*#__PURE__*/ _interopRequireDefault(require("mimic-fn"));
45
+ var _mimicFunction = /*#__PURE__*/ _interopRequireDefault(require("mimic-function"));
46
46
  function _arrayLikeToArray(arr, len) {
47
47
  if (len == null || len > arr.length) len = arr.length;
48
48
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
@@ -219,11 +219,12 @@ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
219
219
  }
220
220
  };
221
221
  var cacheStore = new WeakMap();
222
- function pMemoize(fn) {
223
- var ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _cacheKey = ref.cacheKey, cacheKey = _cacheKey === void 0 ? function(param) {
222
+ function pMemoize(fn, options) {
223
+ var defaultCacheKey = function(param) {
224
224
  var _param = _slicedToArray(param, 1), firstArgument = _param[0];
225
225
  return firstArgument;
226
- } : _cacheKey, _cache = ref.cache, cache = _cache === void 0 ? new Map() : _cache;
226
+ };
227
+ var ref = options !== null && options !== void 0 ? options : {}, _cacheKey = ref.cacheKey, cacheKey = _cacheKey === void 0 ? defaultCacheKey : _cacheKey, _cache = ref.cache, cache = _cache === void 0 ? new Map() : _cache;
227
228
  // Promise objects can't be serialized so we keep track of them internally and only provide their resolved values to `cache`
228
229
  // `Promise<AsyncReturnType<FunctionToMemoize>>` is used instead of `ReturnType<FunctionToMemoize>` because promise properties are not kept
229
230
  var promiseCache = new Map();
@@ -237,15 +238,15 @@ function pMemoize(fn) {
237
238
  }
238
239
  var _this = this;
239
240
  var promise = _asyncToGenerator(function() {
240
- var _tmp, promise, result;
241
+ var _tmp, promise, result, allow, _tmp1;
241
242
  return __generator(this, function(_state) {
242
243
  switch(_state.label){
243
244
  case 0:
244
245
  _state.trys.push([
245
246
  0,
246
247
  ,
247
- 11,
248
- 12
248
+ 14,
249
+ 15
249
250
  ]);
250
251
  _tmp = cache;
251
252
  if (!_tmp) return [
@@ -287,7 +288,7 @@ function pMemoize(fn) {
287
288
  6,
288
289
  ,
289
290
  7,
290
- 10
291
+ 13
291
292
  ]);
292
293
  return [
293
294
  2,
@@ -295,31 +296,57 @@ function pMemoize(fn) {
295
296
  ];
296
297
  case 7:
297
298
  if (!cache) return [
299
+ 3,
300
+ 12
301
+ ];
302
+ if (!(options === null || options === void 0 ? void 0 : options.shouldCache)) return [
298
303
  3,
299
304
  9
300
305
  ];
301
306
  return [
302
307
  4,
303
- cache.set(key, result)
308
+ options.shouldCache(result, {
309
+ key: key,
310
+ argumentsList: arguments_
311
+ })
304
312
  ];
305
313
  case 8:
306
- _state.sent();
307
- _state.label = 9;
308
- case 9:
314
+ _tmp1 = _state.sent();
309
315
  return [
310
- 7
316
+ 3,
317
+ 10
311
318
  ];
319
+ case 9:
320
+ _tmp1 = true;
321
+ _state.label = 10;
312
322
  case 10:
313
- return [
323
+ allow = _tmp1;
324
+ if (!allow) return [
314
325
  3,
315
326
  12
316
327
  ];
328
+ return [
329
+ 4,
330
+ cache.set(key, result)
331
+ ];
317
332
  case 11:
333
+ _state.sent();
334
+ _state.label = 12;
335
+ case 12:
336
+ return [
337
+ 7
338
+ ];
339
+ case 13:
340
+ return [
341
+ 3,
342
+ 15
343
+ ];
344
+ case 14:
318
345
  promiseCache.delete(key);
319
346
  return [
320
347
  7
321
348
  ];
322
- case 12:
349
+ case 15:
323
350
  return [
324
351
  2
325
352
  ];
@@ -329,7 +356,7 @@ function pMemoize(fn) {
329
356
  promiseCache.set(key, promise);
330
357
  return promise;
331
358
  };
332
- (0, _mimicFn.default)(memoized, fn, {
359
+ (0, _mimicFunction.default)(memoized, fn, {
333
360
  ignoreNonConfigurable: true
334
361
  });
335
362
  cacheStore.set(memoized, cache);
@@ -337,22 +364,22 @@ function pMemoize(fn) {
337
364
  }
338
365
  function pMemoizeDecorator() {
339
366
  var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
340
- var instanceMap = new WeakMap();
341
- return function(target, propertyKey, descriptor) {
342
- var input = target[propertyKey]; // eslint-disable-line @typescript-eslint/no-unsafe-assignment
343
- if (typeof input !== "function") {
344
- throw new TypeError("The decorated value must be a function");
367
+ return function(value, context) {
368
+ if (context.kind !== "method") {
369
+ throw new TypeError("pMemoizeDecorator can only decorate methods");
345
370
  }
346
- delete descriptor.value;
347
- delete descriptor.writable;
348
- descriptor.get = function() {
349
- if (!instanceMap.has(this)) {
350
- var value = pMemoize(input, options);
351
- instanceMap.set(this, value);
352
- return value;
353
- }
354
- return instanceMap.get(this);
355
- };
371
+ if (context.private) {
372
+ throw new TypeError("pMemoizeDecorator cannot decorate private methods");
373
+ }
374
+ context.addInitializer(function() {
375
+ var memoizedMethod = pMemoize(value, options);
376
+ Object.defineProperty(this, context.name, {
377
+ configurable: true,
378
+ writable: true,
379
+ enumerable: false,
380
+ value: memoizedMethod
381
+ });
382
+ });
356
383
  };
357
384
  }
358
385
  function pMemoizeClear(fn) {
package/package.json CHANGED
@@ -1,14 +1,19 @@
1
1
  {
2
2
  "name": "@common.js/p-memoize",
3
- "version": "7.1.1",
3
+ "version": "8.0.1",
4
4
  "description": "p-memoize package exported as CommonJS modules",
5
5
  "license": "MIT",
6
6
  "repository": "etienne-martin/common.js",
7
7
  "funding": "https://github.com/sindresorhus/p-memoize?sponsor=1",
8
8
  "type": "commonjs",
9
9
  "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "sideEffects": false,
10
15
  "engines": {
11
- "node": ">=14.16"
16
+ "node": ">=20"
12
17
  },
13
18
  "scripts": {
14
19
  "test": "xo && ava && npm run build && tsd",
@@ -18,28 +23,31 @@
18
23
  "dist"
19
24
  ],
20
25
  "dependencies": {
21
- "@common.js/mimic-fn": "^4.0.0",
22
- "type-fest": "^3.0.0"
26
+ "mimic-function": "npm:@common.js/mimic-function@5.0.2",
27
+ "type-fest": "^4.41.0"
23
28
  },
24
29
  "devDependencies": {
25
- "@sindresorhus/tsconfig": "^3.0.1",
26
- "@types/serialize-javascript": "^5.0.2",
27
- "ava": "^4.3.3",
28
- "del-cli": "^5.0.0",
29
- "delay": "^5.0.0",
30
- "p-defer": "^4.0.0",
31
- "p-state": "^1.0.0",
32
- "serialize-javascript": "^6.0.0",
33
- "ts-node": "^10.9.1",
34
- "tsd": "^0.24.1",
35
- "xo": "^0.52.4"
30
+ "@sindresorhus/tsconfig": "^8.0.1",
31
+ "@types/serialize-javascript": "^5.0.4",
32
+ "ava": "^6.4.1",
33
+ "del-cli": "^6.0.0",
34
+ "delay": "^6.0.0",
35
+ "p-defer": "^4.0.1",
36
+ "p-state": "^2.0.1",
37
+ "serialize-javascript": "^6.0.2",
38
+ "tsd": "^0.33.0",
39
+ "tsimp": "^2.0.12",
40
+ "xo": "^1.2.1"
36
41
  },
37
42
  "ava": {
43
+ "environmentVariables": {
44
+ "TSIMP_DIAG": "ignore"
45
+ },
38
46
  "extensions": {
39
47
  "ts": "module"
40
48
  },
41
49
  "nodeArguments": [
42
- "--loader=ts-node/esm"
50
+ "--import=tsimp/import"
43
51
  ]
44
52
  },
45
53
  "xo": {
@@ -48,5 +56,13 @@
48
56
  }
49
57
  },
50
58
  "homepage": "https://github.com/etienne-martin/common.js#readme",
59
+ "commonjs": {
60
+ "source": {
61
+ "name": "p-memoize",
62
+ "version": "8.0.0"
63
+ },
64
+ "transformRevision": 1,
65
+ "buildKey": "3d7fee255a1f5ce8a0652ddb6d3fa472cda05272baa8ee4e5985b8b4d3ee22ab"
66
+ },
51
67
  "main": "./dist/index.js"
52
68
  }