@dxos/async 0.8.4-main.fbb7a13 → 0.8.4-main.fcfe5033a5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/async",
3
- "version": "0.8.4-main.fbb7a13",
3
+ "version": "0.8.4-main.fcfe5033a5",
4
4
  "description": "Async utilities.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -33,12 +33,12 @@
33
33
  "dependencies": {
34
34
  "zen-observable": "^0.10.0",
35
35
  "zen-push": "^0.3.1",
36
- "@dxos/context": "0.8.4-main.fbb7a13",
37
- "@dxos/debug": "0.8.4-main.fbb7a13",
38
- "@dxos/invariant": "0.8.4-main.fbb7a13",
39
- "@dxos/log": "0.8.4-main.fbb7a13",
40
- "@dxos/util": "0.8.4-main.fbb7a13",
41
- "@dxos/node-std": "0.8.4-main.fbb7a13"
36
+ "@dxos/context": "0.8.4-main.fcfe5033a5",
37
+ "@dxos/debug": "0.8.4-main.fcfe5033a5",
38
+ "@dxos/invariant": "0.8.4-main.fcfe5033a5",
39
+ "@dxos/util": "0.8.4-main.fcfe5033a5",
40
+ "@dxos/log": "0.8.4-main.fcfe5033a5",
41
+ "@dxos/node-std": "0.8.4-main.fcfe5033a5"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/zen-observable": "^0.8.3"
package/src/cleanup.ts CHANGED
@@ -10,9 +10,12 @@ export type CleanupFn = () => void;
10
10
  * Combine multiple cleanup functions into a single cleanup function.
11
11
  * Can be used in effect hooks in conjunction with `addEventListener`.
12
12
  */
13
- export const combine = (...cleanupFns: (CleanupFn | CleanupFn[])[]): CleanupFn => {
13
+ export const combine = (...cleanupFns: (boolean | undefined | CleanupFn | CleanupFn[])[]): CleanupFn => {
14
14
  return () => {
15
- cleanupFns.flat().forEach((cleanupFn) => cleanupFn());
15
+ cleanupFns
16
+ .flat()
17
+ .filter((f): f is CleanupFn => typeof f === 'function')
18
+ .forEach((cleanupFn) => cleanupFn());
16
19
  };
17
20
  };
18
21
 
@@ -37,7 +40,6 @@ type EventMap<T> = T extends Window
37
40
  /**
38
41
  * Add the event listener and return a cleanup function.
39
42
  * Can be used in effect hooks in conjunction with `combine`.
40
- * @deprecated use bind-event-listener
41
43
  */
42
44
  export const addEventListener = <T extends EventTarget, K extends keyof EventMap<T>>(
43
45
  target: T,
@@ -52,8 +54,8 @@ export const addEventListener = <T extends EventTarget, K extends keyof EventMap
52
54
  export class SubscriptionList {
53
55
  private readonly _cleanups: CleanupFn[] = [];
54
56
 
55
- add(cb: CleanupFn): this {
56
- this._cleanups.push(cb);
57
+ add(...cb: CleanupFn[]): this {
58
+ this._cleanups.push(...cb);
57
59
  return this;
58
60
  }
59
61
 
package/src/debounce.ts CHANGED
@@ -12,7 +12,7 @@ type Callback = (...args: any[]) => void;
12
12
  * @param delay Time to wait before invoking the callback.
13
13
  * @returns A new function that schedules the callback once and ignores subsequent calls until executed.
14
14
  */
15
- export const delay = <CB extends Callback>(cb: CB, delay = 100): CB => {
15
+ export const delay = <F extends Callback>(cb: F, delay = 100): F => {
16
16
  let pending = false;
17
17
  return ((...args: any[]) => {
18
18
  if (pending) {
@@ -27,32 +27,37 @@ export const delay = <CB extends Callback>(cb: CB, delay = 100): CB => {
27
27
  pending = false;
28
28
  }
29
29
  }, delay);
30
- }) as CB;
30
+ }) as F;
31
31
  };
32
32
 
33
33
  /**
34
- * Debounce callback.
34
+ * Debounce callback: delays execution until calls stop.
35
+ * Each new call resets the timer, so the callback fires only after the delay elapses with no further calls (trailing-edge).
36
+ * Use when you want to react to the end of a burst of events (e.g. user stops typing).
35
37
  *
36
38
  * @param cb Callback to invoke.
37
- * @param delay Time window to wait before allowing calls.
38
- * @returns A new function that wraps the callback and ensures that the callback is only invoked after the time window has passed and no new calls have been made.
39
+ * @param delay Idle time (ms) to wait after the last call before invoking.
40
+ * @returns Wrapped function that postpones invocation until activity ceases.
39
41
  */
40
- export const debounce = <CB extends Callback>(cb: CB, delay = 100): CB => {
42
+ export const debounce = <F extends Callback>(cb: F, delay = 100): F => {
41
43
  let t: ReturnType<typeof setTimeout>;
42
44
  return ((...args: any[]) => {
43
45
  clearTimeout(t);
44
46
  t = setTimeout(() => cb(...args), delay);
45
- }) as CB;
47
+ }) as F;
46
48
  };
47
49
 
48
50
  /**
49
- * Throttle callback.
51
+ * Throttle callback: limits execution to at most once per interval.
52
+ * The callback fires immediately on the first call;
53
+ * subsequent calls within the same interval are dropped (leading-edge).
54
+ * Use when you need regular updates at a bounded rate (e.g. scroll or resize handlers).
50
55
  *
51
56
  * @param cb Callback to invoke.
52
- * @param delay Time window to allow calls in.
53
- * @returns A new function that wraps the callback and prevents multiple invocations within the time window.
57
+ * @param delay Minimum interval (ms) between successive invocations.
58
+ * @returns Wrapped function that rate-limits invocations.
54
59
  */
55
- export const throttle = <CB extends Callback>(cb: CB, delay = 100): CB => {
60
+ export const throttle = <F extends Callback>(cb: F, delay = 100): F => {
56
61
  let lastCall = 0;
57
62
  return ((...args: any[]) => {
58
63
  const now = Date.now();
@@ -60,7 +65,7 @@ export const throttle = <CB extends Callback>(cb: CB, delay = 100): CB => {
60
65
  cb(...args);
61
66
  lastCall = now;
62
67
  }
63
- }) as CB;
68
+ }) as F;
64
69
  };
65
70
 
66
71
  /**
@@ -72,7 +77,7 @@ export const throttle = <CB extends Callback>(cb: CB, delay = 100): CB => {
72
77
  * @param delay Time window for both throttle and debounce.
73
78
  * @returns A new function that combines throttle and debounce behavior.
74
79
  */
75
- export const debounceAndThrottle = <CB extends Callback>(cb: CB, delay = 100): CB => {
80
+ export const debounceAndThrottle = <F extends Callback>(cb: F, delay = 100): F => {
76
81
  let timeout: ReturnType<typeof setTimeout>;
77
82
  let lastCall = 0;
78
83
 
@@ -94,5 +99,5 @@ export const debounceAndThrottle = <CB extends Callback>(cb: CB, delay = 100): C
94
99
  lastCall = Date.now();
95
100
  }, delay - delta);
96
101
  }
97
- }) as CB;
102
+ }) as F;
98
103
  };
@@ -3,7 +3,6 @@
3
3
  //
4
4
 
5
5
  import { EventEmitter } from 'node:events';
6
-
7
6
  import { describe, expect, test } from 'vitest';
8
7
 
9
8
  import { onEvent, waitForEvent } from './event-emitter';
@@ -66,8 +66,10 @@ export interface CancellableObservableEvents {
66
66
  /**
67
67
  * @deprecated
68
68
  */
69
- export interface CancellableObservable<Events extends CancellableObservableEvents, Value = unknown>
70
- extends ObservableValue<Events, Value> {
69
+ export interface CancellableObservable<
70
+ Events extends CancellableObservableEvents,
71
+ Value = unknown,
72
+ > extends ObservableValue<Events, Value> {
71
73
  cancel(): Promise<void>;
72
74
  }
73
75
 
@@ -2,7 +2,7 @@
2
2
  // Copyright 2022 DXOS.org
3
3
  //
4
4
 
5
- import { type Context, ContextDisposedError } from '@dxos/context';
5
+ import { Context, ContextDisposedError } from '@dxos/context';
6
6
  import { StackTrace } from '@dxos/debug';
7
7
  import { type MaybePromise } from '@dxos/util';
8
8
 
@@ -98,17 +98,17 @@ export class AsyncTask {
98
98
  * Context of the resource that owns the task.
99
99
  * When the context is disposed, the task is cancelled and cannot be scheduled again.
100
100
  */
101
- // TODO(dmaretskyi): We don't really need to pass ctx in here, since close will also signal dispose.
102
- open(ctx: Context): void {
103
- this.#ctx = ctx;
101
+ open(): void {
102
+ this.#ctx = new Context();
104
103
  }
105
104
 
106
105
  /**
107
106
  * Closes the task and waits for it to finish if it is running.
108
107
  */
109
108
  async close(): Promise<void> {
110
- this.#ctx = undefined;
109
+ await this.#ctx?.dispose();
111
110
  await this.join();
111
+ this.#ctx = undefined;
112
112
  }
113
113
 
114
114
  [Symbol.asyncDispose](): Promise<void> {
@@ -118,6 +118,7 @@ export class AsyncTask {
118
118
  /**
119
119
  * Schedule the task to run asynchronously.
120
120
  */
121
+ // TODO(dmaretskyi): Add scheduleAt. Where the earlier time will override the later one.
121
122
  schedule(): void {
122
123
  if (!this.#ctx || this.#ctx.disposed) {
123
124
  throw new Error('AsyncTask not open');
package/src/timeout.ts CHANGED
@@ -4,7 +4,6 @@
4
4
 
5
5
  import { type Context, ContextDisposedError } from '@dxos/context';
6
6
 
7
- import { promiseFromCallback } from './callback';
8
7
  import { TimeoutError } from './errors';
9
8
 
10
9
  /**
@@ -57,12 +56,11 @@ export const asyncReturn = () => sleep(0);
57
56
  /**
58
57
  * Wait for promise or throw error.
59
58
  */
60
- export const asyncTimeout = async <T>(
61
- // TODO(dmaretskyi): This callback API is unintuitive and leads to bugs.
62
- promise: Promise<T> | (() => Promise<T>),
63
- timeout: number,
64
- err?: Error | string,
65
- ): Promise<T> => {
59
+ export const asyncTimeout = async <T>(promise: Promise<T>, timeout: number, err?: Error | string): Promise<T> => {
60
+ if (typeof promise === 'function') {
61
+ throw new Error('First argument must be a promise.');
62
+ }
63
+
66
64
  let timeoutId: NodeJS.Timeout;
67
65
  const throwable = err === undefined || typeof err === 'string' ? new TimeoutError(timeout, err) : err;
68
66
  const timeoutPromise = new Promise<T>((resolve, reject) => {
@@ -73,8 +71,7 @@ export const asyncTimeout = async <T>(
73
71
  unrefTimeout(timeoutId);
74
72
  });
75
73
 
76
- const conditionTimeout = typeof promise === 'function' ? promiseFromCallback<T>(promise) : promise;
77
- return await Promise.race([conditionTimeout, timeoutPromise]).finally(() => {
74
+ return await Promise.race([promise, timeoutPromise]).finally(() => {
78
75
  clearTimeout(timeoutId);
79
76
  });
80
77
  };