@oscarpalmer/atoms 0.148.0 → 0.150.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.
@@ -3009,60 +3009,22 @@ var CancelablePromise = class extends Promise {
3009
3009
  };
3010
3010
  var PromiseTimeoutError = class extends Error {
3011
3011
  constructor() {
3012
- super(MESSAGE_TIMEOUT);
3013
- this.name = ERROR_NAME$1;
3012
+ super(PROMISE_MESSAGE_TIMEOUT);
3013
+ this.name = PROMISE_ERROR_NAME;
3014
3014
  }
3015
3015
  };
3016
- async function attemptPromise(value, options) {
3017
- const isFunction = typeof value === "function";
3018
- if (!isFunction && !(value instanceof Promise)) return Promise.reject(new TypeError(MESSAGE_EXPECTATION_ATTEMPT));
3019
- const { signal, time } = getPromiseOptions(options);
3020
- if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3021
- function abort() {
3022
- rejector(signal.reason);
3023
- }
3024
- async function handler(resolve, reject) {
3025
- try {
3026
- let result = isFunction ? value() : await value;
3027
- if (result instanceof Promise) result = await result;
3028
- settlePromise(abort, resolve, result, signal);
3029
- } catch (error) {
3030
- settlePromise(abort, reject, error, signal);
3031
- }
3032
- }
3033
- let rejector;
3034
- signal?.addEventListener(EVENT_NAME$1, abort, ABORT_OPTIONS);
3035
- const promise = new Promise((resolve, reject) => {
3036
- rejector = reject;
3037
- handler(resolve, reject);
3038
- });
3039
- return time > 0 ? getTimed(promise, time, signal) : promise;
3040
- }
3041
- /**
3042
- * Create a cancelable promise
3043
- * @param executor Executor function for the promise
3044
- * @returns Cancelable promise
3045
- */
3046
- function cancelable(executor) {
3047
- return new CancelablePromise(executor);
3048
- }
3049
- function delay(options) {
3050
- const { signal, time } = getPromiseOptions(options);
3051
- if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3052
- function abort() {
3053
- clearTimeout(timeout);
3054
- rejector(signal.reason);
3055
- }
3056
- signal?.addEventListener("abort", abort, ABORT_OPTIONS);
3057
- let rejector;
3058
- let timeout;
3059
- return new Promise((resolve, reject) => {
3060
- rejector = reject;
3061
- timeout = setTimeout(() => {
3062
- settlePromise(abort, resolve, void 0, signal);
3063
- }, time);
3064
- });
3065
- }
3016
+ const PROMISE_ABORT_OPTIONS = { once: true };
3017
+ const PROMISE_ERROR_NAME = "PromiseTimeoutError";
3018
+ const PROMISE_EVENT_NAME = "abort";
3019
+ const PROMISE_MESSAGE_EXPECTATION_ATTEMPT = "Attempt expected a function or a promise";
3020
+ const PROMISE_MESSAGE_EXPECTATION_PROMISES = "Promises expected an array of promises";
3021
+ const PROMISE_MESSAGE_EXPECTATION_RESULT = "toResult expected a Promise";
3022
+ const PROMISE_MESSAGE_EXPECTATION_TIMED = "Timed function expected a Promise";
3023
+ const PROMISE_MESSAGE_TIMEOUT = "Promise timed out";
3024
+ const PROMISE_STRATEGY_ALL = new Set(["complete", "first"]);
3025
+ const PROMISE_STRATEGY_DEFAULT = "complete";
3026
+ const PROMISE_TYPE_FULFILLED = "fulfilled";
3027
+ const PROMISE_TYPE_REJECTED = "rejected";
3066
3028
  function getNumberOrDefault$1(value) {
3067
3029
  return typeof value === "number" && value > 0 ? value : 0;
3068
3030
  }
@@ -3082,7 +3044,7 @@ function getPromisesOptions(input) {
3082
3044
  if (typeof input === "string") return { strategy: getStrategyOrDefault(input) };
3083
3045
  if (input instanceof AbortSignal) return {
3084
3046
  signal: input,
3085
- strategy: DEFAULT_STRATEGY
3047
+ strategy: PROMISE_STRATEGY_DEFAULT
3086
3048
  };
3087
3049
  const options = typeof input === "object" && input !== null ? input : {};
3088
3050
  return {
@@ -3091,35 +3053,81 @@ function getPromisesOptions(input) {
3091
3053
  };
3092
3054
  }
3093
3055
  function getStrategyOrDefault(value) {
3094
- return strategies.has(value) ? value : DEFAULT_STRATEGY;
3056
+ return PROMISE_STRATEGY_ALL.has(value) ? value : PROMISE_STRATEGY_DEFAULT;
3095
3057
  }
3096
- async function getTimed(promise, time, signal) {
3097
- function abort() {
3098
- clearTimeout(timeout);
3099
- rejector(signal.reason);
3100
- }
3101
- signal?.addEventListener(EVENT_NAME$1, abort, ABORT_OPTIONS);
3102
- let rejector;
3103
- let timeout;
3104
- return Promise.race([promise, new Promise((_, reject) => {
3105
- rejector = reject;
3106
- timeout = setTimeout(() => {
3107
- settlePromise(abort, reject, new PromiseTimeoutError(), signal);
3108
- }, time);
3109
- })]).then((value) => {
3110
- clearTimeout(timeout);
3111
- signal?.removeEventListener(EVENT_NAME$1, abort);
3112
- return value;
3113
- });
3058
+ /**
3059
+ * Is the value a fulfilled promise result?
3060
+ * @param value Value to check
3061
+ * @returns `true` if the value is a fulfilled promise result, `false` otherwise
3062
+ */
3063
+ function isFulfilled(value) {
3064
+ return isType(value, PROMISE_TYPE_FULFILLED);
3065
+ }
3066
+ /**
3067
+ * Is the value a rejected promise result?
3068
+ * @param value Value to check
3069
+ * @returns `true` if the value is a rejected promise result, `false` otherwise
3070
+ */
3071
+ function isRejected(value) {
3072
+ return isType(value, PROMISE_TYPE_REJECTED);
3073
+ }
3074
+ function isType(value, type) {
3075
+ return typeof value === "object" && value !== null && value.status === type;
3076
+ }
3077
+ function error(value, original) {
3078
+ return getError(value, original);
3079
+ }
3080
+ function getError(value, original) {
3081
+ const errorResult = {
3082
+ error: value,
3083
+ ok: false
3084
+ };
3085
+ if (original instanceof Error) errorResult.original = original;
3086
+ return errorResult;
3087
+ }
3088
+ /**
3089
+ * Creates an ok result
3090
+ * @param value Value
3091
+ * @returns Ok result
3092
+ */
3093
+ function ok(value) {
3094
+ return {
3095
+ ok: true,
3096
+ value
3097
+ };
3098
+ }
3099
+ /**
3100
+ * Converts a result to a promise
3101
+ *
3102
+ * Resolves if ok, rejects for error
3103
+ * @param result Result to convert
3104
+ * @returns Promised result
3105
+ */
3106
+ async function toPromise(result) {
3107
+ const actual = typeof result === "function" ? result() : result;
3108
+ if (!isResult(actual)) return Promise.reject(new Error(MESSAGE_PROMISE_RESULT));
3109
+ return isOk(actual) ? Promise.resolve(actual.value) : Promise.reject(actual.error);
3110
+ }
3111
+ function unwrap(value, defaultValue) {
3112
+ return isOk(value) ? value.value : defaultValue;
3113
+ }
3114
+ const MESSAGE_PROMISE_RESULT = "toPromise expected to receive a Result";
3115
+ /**
3116
+ * Create a cancelable promise
3117
+ * @param executor Executor function for the promise
3118
+ * @returns Cancelable promise
3119
+ */
3120
+ function cancelable(executor) {
3121
+ return new CancelablePromise(executor);
3114
3122
  }
3115
3123
  function handleResult(status, parameters) {
3116
3124
  const { abort, complete, data, handlers, index, signal, value } = parameters;
3117
3125
  if (signal?.aborted ?? false) return;
3118
- if (!complete && status === TYPE_REJECTED) {
3126
+ if (!complete && status === PROMISE_TYPE_REJECTED) {
3119
3127
  settlePromise(abort, handlers.reject, value, signal);
3120
3128
  return;
3121
3129
  }
3122
- data.result[index] = !complete ? value : status === TYPE_FULFILLED ? {
3130
+ data.result[index] = !complete ? value : status === PROMISE_TYPE_FULFILLED ? {
3123
3131
  status,
3124
3132
  value
3125
3133
  } : {
@@ -3128,37 +3136,105 @@ function handleResult(status, parameters) {
3128
3136
  };
3129
3137
  if (index === data.last) settlePromise(abort, handlers.resolve, data.result, signal);
3130
3138
  }
3131
- /**
3132
- * Is the value a fulfilled promise result?
3133
- * @param value Value to check
3134
- * @returns `true` if the value is a fulfilled promise result, `false` otherwise
3135
- */
3136
- function isFulfilled(value) {
3137
- return isType(value, TYPE_FULFILLED);
3139
+ function settlePromise(aborter, settler, value, signal) {
3140
+ signal?.removeEventListener(PROMISE_EVENT_NAME, aborter);
3141
+ settler(value);
3138
3142
  }
3139
- /**
3140
- * Is the value a rejected promise result?
3141
- * @param value Value to check
3142
- * @returns `true` if the value is a rejected promise result, `false` otherwise
3143
- */
3144
- function isRejected(value) {
3145
- return isType(value, TYPE_REJECTED);
3143
+ async function toResult(value) {
3144
+ const actual = typeof value === "function" ? value() : value;
3145
+ if (!(actual instanceof Promise)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_RESULT));
3146
+ return actual.then((result) => ok(result)).catch((reason) => error(reason));
3146
3147
  }
3147
- function isType(value, type) {
3148
- return typeof value === "object" && value !== null && value.status === type;
3148
+ async function getTimedPromise(promise, time, signal) {
3149
+ function abort() {
3150
+ cancelAnimationFrame(frame);
3151
+ rejector(signal.reason);
3152
+ }
3153
+ function run(now) {
3154
+ start ??= now;
3155
+ if (time === 0 || now - start >= time - 5) settlePromise(abort, rejector, new PromiseTimeoutError(), signal);
3156
+ else frame = requestAnimationFrame(run);
3157
+ }
3158
+ signal?.addEventListener(PROMISE_EVENT_NAME, abort, PROMISE_ABORT_OPTIONS);
3159
+ let frame;
3160
+ let rejector;
3161
+ let start;
3162
+ return Promise.race([promise, new Promise((_, reject) => {
3163
+ rejector = reject;
3164
+ frame = requestAnimationFrame(run);
3165
+ })]).then((value) => {
3166
+ cancelAnimationFrame(frame);
3167
+ signal?.removeEventListener(PROMISE_EVENT_NAME, abort);
3168
+ return value;
3169
+ });
3170
+ }
3171
+ async function timed(promise, options) {
3172
+ if (!(promise instanceof Promise)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_TIMED));
3173
+ const { signal, time } = getPromiseOptions(options);
3174
+ if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3175
+ return time > 0 ? getTimedPromise(promise, time, signal) : promise;
3176
+ }
3177
+ function delay(options) {
3178
+ const { signal, time } = getPromiseOptions(options);
3179
+ if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3180
+ function abort() {
3181
+ cancelAnimationFrame(frame);
3182
+ rejector(signal.reason);
3183
+ }
3184
+ function run(now) {
3185
+ start ??= now;
3186
+ if (now - start >= time - 5) settlePromise(abort, resolver, void 0, signal);
3187
+ else frame = requestAnimationFrame(run);
3188
+ }
3189
+ signal?.addEventListener("abort", abort, PROMISE_ABORT_OPTIONS);
3190
+ let frame;
3191
+ let rejector;
3192
+ let resolver;
3193
+ let start;
3194
+ return new Promise((resolve, reject) => {
3195
+ rejector = reject;
3196
+ resolver = resolve;
3197
+ if (time === 0) settlePromise(abort, resolve, void 0, signal);
3198
+ else frame = requestAnimationFrame(run);
3199
+ });
3200
+ }
3201
+ async function attemptPromise(value, options) {
3202
+ const isFunction = typeof value === "function";
3203
+ if (!isFunction && !(value instanceof Promise)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_ATTEMPT));
3204
+ const { signal, time } = getPromiseOptions(options);
3205
+ if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3206
+ function abort() {
3207
+ rejector(signal.reason);
3208
+ }
3209
+ async function handler(resolve, reject) {
3210
+ try {
3211
+ let result = isFunction ? value() : await value;
3212
+ if (result instanceof Promise) result = await result;
3213
+ settlePromise(abort, resolve, result, signal);
3214
+ } catch (error) {
3215
+ settlePromise(abort, reject, error, signal);
3216
+ }
3217
+ }
3218
+ let rejector;
3219
+ signal?.addEventListener(PROMISE_EVENT_NAME, abort, PROMISE_ABORT_OPTIONS);
3220
+ const promise = new Promise((resolve, reject) => {
3221
+ rejector = reject;
3222
+ handler(resolve, reject);
3223
+ });
3224
+ return time > 0 ? getTimedPromise(promise, time, signal) : promise;
3149
3225
  }
3150
3226
  async function promises(items, options) {
3151
3227
  const { signal, strategy } = getPromisesOptions(options);
3152
3228
  if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3153
- if (!Array.isArray(items)) return Promise.reject(new TypeError(MESSAGE_EXPECTATION_PROMISES));
3229
+ if (!Array.isArray(items)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_PROMISES));
3154
3230
  const actual = items.filter((item) => item instanceof Promise);
3155
3231
  const { length } = actual;
3156
3232
  if (length === 0) return actual;
3157
- const complete = strategy === DEFAULT_STRATEGY;
3233
+ const complete = strategy === PROMISE_STRATEGY_DEFAULT;
3158
3234
  function abort() {
3159
3235
  handlers.reject(signal.reason);
3160
3236
  }
3161
- signal?.addEventListener("abort", abort, ABORT_OPTIONS);
3237
+ signal?.addEventListener("abort", abort, PROMISE_ABORT_OPTIONS);
3162
3238
  const data = {
3163
3239
  last: length - 1,
3164
3240
  result: []
@@ -3169,7 +3245,7 @@ async function promises(items, options) {
3169
3245
  reject,
3170
3246
  resolve
3171
3247
  };
3172
- for (let index = 0; index < length; index += 1) actual[index].then((value) => handleResult(TYPE_FULFILLED, {
3248
+ for (let index = 0; index < length; index += 1) actual[index].then((value) => handleResult(PROMISE_TYPE_FULFILLED, {
3173
3249
  abort,
3174
3250
  complete,
3175
3251
  data,
@@ -3177,7 +3253,7 @@ async function promises(items, options) {
3177
3253
  index,
3178
3254
  signal,
3179
3255
  value
3180
- })).catch((reason) => handleResult(TYPE_REJECTED, {
3256
+ })).catch((reason) => handleResult(PROMISE_TYPE_REJECTED, {
3181
3257
  abort,
3182
3258
  complete,
3183
3259
  data,
@@ -3188,27 +3264,6 @@ async function promises(items, options) {
3188
3264
  }));
3189
3265
  });
3190
3266
  }
3191
- function settlePromise(aborter, settler, value, signal) {
3192
- signal?.removeEventListener(EVENT_NAME$1, aborter);
3193
- settler(value);
3194
- }
3195
- async function timed(promise, options) {
3196
- if (!(promise instanceof Promise)) return Promise.reject(new TypeError(MESSAGE_EXPECTATION_TIMED));
3197
- const { signal, time } = getPromiseOptions(options);
3198
- if (signal?.aborted ?? false) return Promise.reject(signal.reason);
3199
- return time > 0 ? getTimed(promise, time, signal) : promise;
3200
- }
3201
- const ABORT_OPTIONS = { once: true };
3202
- const DEFAULT_STRATEGY = "complete";
3203
- const ERROR_NAME$1 = "PromiseTimeoutError";
3204
- const EVENT_NAME$1 = "abort";
3205
- const MESSAGE_EXPECTATION_ATTEMPT = "Attempt expected a function or a promise";
3206
- const MESSAGE_EXPECTATION_PROMISES = "Promises expected an array of promises";
3207
- const MESSAGE_EXPECTATION_TIMED = "Timed function expected a Promise";
3208
- const MESSAGE_TIMEOUT = "Promise timed out";
3209
- const strategies = new Set(["complete", "first"]);
3210
- const TYPE_FULFILLED = "fulfilled";
3211
- const TYPE_REJECTED = "rejected";
3212
3267
  /**
3213
3268
  * Convert a query string to a plain _(nested)_ object
3214
3269
  * @param query Query string to convert
@@ -3536,6 +3591,29 @@ const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
3536
3591
  const BOOLEAN_MODIFIER = .5;
3537
3592
  const HEX_CHARACTERS = "0123456789ABCDEF";
3538
3593
  const HEX_MAXIMUM = 15;
3594
+ async function asyncMatchResult(result, first, error) {
3595
+ let value;
3596
+ if (typeof result === "function") value = await result();
3597
+ else if (result instanceof Promise) value = await result;
3598
+ else value = result;
3599
+ if (!isResult(value)) throw new Error(MESSAGE_RESULT);
3600
+ const hasObj = typeof first === "object" && first !== null;
3601
+ const okHandler = hasObj ? first.ok : first;
3602
+ const errorHandler = hasObj ? first.error : error;
3603
+ if (isOk(value)) return okHandler(value.value);
3604
+ return errorHandler(value.error, value.original);
3605
+ }
3606
+ function matchResult(result, first, error) {
3607
+ const value = typeof result === "function" ? result() : result;
3608
+ if (!isResult(value)) throw new Error(MESSAGE_RESULT);
3609
+ const hasObj = typeof first === "object" && first !== null;
3610
+ const okHandler = hasObj ? first.ok : first;
3611
+ const errorHandler = hasObj ? first.error : error;
3612
+ if (isOk(value)) return okHandler(value.value);
3613
+ return errorHandler(value.error, value.original);
3614
+ }
3615
+ matchResult.async = asyncMatchResult;
3616
+ const MESSAGE_RESULT = "`result.match` expected a Result or a function that returns a Result";
3539
3617
  function attemptAsyncFlow(...fns) {
3540
3618
  let Flow;
3541
3619
  return (...args) => attempt.async(() => {
@@ -3592,33 +3670,9 @@ function attempt(callback, err) {
3592
3670
  }
3593
3671
  attempt.async = asyncAttempt;
3594
3672
  attempt.flow = attemptFlow;
3673
+ attempt.match = matchResult;
3595
3674
  attempt.pipe = attemptPipe;
3596
3675
  attempt.promise = attemptPromise;
3597
- function error(value, original) {
3598
- return getError(value, original);
3599
- }
3600
- function getError(value, original) {
3601
- const errorResult = {
3602
- error: value,
3603
- ok: false
3604
- };
3605
- if (original instanceof Error) errorResult.original = original;
3606
- return errorResult;
3607
- }
3608
- /**
3609
- * Creates an ok result
3610
- * @param value Value
3611
- * @returns Ok result
3612
- */
3613
- function ok(value) {
3614
- return {
3615
- ok: true,
3616
- value
3617
- };
3618
- }
3619
- function unwrap(value, defaultValue) {
3620
- return isOk(value) ? value.value : defaultValue;
3621
- }
3622
3676
  /**
3623
3677
  * - A Set with a maximum size
3624
3678
  * - Behavior is similar to a _LRU_-cache, where the oldest values are removed
@@ -3671,4 +3725,4 @@ var SizedSet = class extends Set {
3671
3725
  }
3672
3726
  }
3673
3727
  };
3674
- export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, fromQuery, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, times, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
3728
+ export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, toResult as fromPromise, toResult, fromQuery, toPromise as fromResult, toPromise, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, times, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
package/dist/index.js CHANGED
@@ -60,10 +60,16 @@ import { unsmush } from "./value/unsmush.js";
60
60
  import { isEmpty, isInstanceOf, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumerical, isObject, isPrimitive } from "./is.js";
61
61
  import { logger } from "./logger.js";
62
62
  import { average, ceil, count, floor, median, min, round, sum } from "./math.js";
63
- import { CancelablePromise, PromiseTimeoutError, attemptPromise, cancelable, delay, isFulfilled, isRejected, promises, timed } from "./promise.js";
63
+ import { CancelablePromise, PromiseTimeoutError } from "./promise/models.js";
64
+ import { isFulfilled, isRejected } from "./promise/helpers.js";
65
+ import { error, ok, toPromise, unwrap } from "./result/misc.js";
66
+ import { cancelable, toResult } from "./promise/misc.js";
67
+ import { timed } from "./promise/timed.js";
68
+ import { delay } from "./promise/delay.js";
69
+ import { attemptPromise, promises } from "./promise/index.js";
64
70
  import { fromQuery, toQuery } from "./query.js";
65
71
  import { QueueError, queue } from "./queue.js";
66
72
  import { getRandomBoolean, getRandomCharacters, getRandomColor, getRandomHex, getRandomItem, getRandomItems } from "./random.js";
67
- import { attempt, error, ok, unwrap } from "./result/index.js";
73
+ import { attempt } from "./result/index.js";
68
74
  import { SizedSet } from "./sized/set.js";
69
- export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, fromQuery, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, times, titleCase, toMap, toQuery, toRecord, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
75
+ export { CancelablePromise, frame_rate_default as FRAME_RATE_MS, PromiseTimeoutError, QueueError, SizedMap, SizedSet, attempt, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, count, debounce, delay, diff, endsWith, equal, error, exists, filter, find, flatten, floor, flow, toResult as fromPromise, fromQuery, toPromise as fromResult, getArray, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getString, getUuid, getValue, groupBy, hexToHsl, hexToHsla, hexToRgb, hexToRgba, hslToHex, hslToRgb, hslToRgba, ignoreKey, includes, indexOf, insert, isArrayOrPlainObject, isColor, isConstructor, isEmpty, isError, isFulfilled, isHexColor, isHslColor, isHslLike, isHslaColor, isInstanceOf, isKey, isNonNullable, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isOk, isPlainObject, isPrimitive, isRejected, isResult, isRgbColor, isRgbLike, isRgbaColor, isTypedArray, join, kebabCase, logger, lowerCase, max, median, memoize, merge, min, noop, ok, omit, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, rgbToHex, rgbToHsl, rgbToHsla, round, select, setValue, shuffle, smush, snakeCase, sort, splice, startsWith, sum, template, throttle, timed, times, titleCase, toMap, toPromise, toQuery, toRecord, toResult, toSet, toggle, trim, truncate, tryDecode, tryEncode, unique, unsmush, unwrap, update, upperCase, words };
@@ -0,0 +1,28 @@
1
+ import { PROMISE_ABORT_OPTIONS } from "./models.js";
2
+ import { getPromiseOptions } from "./helpers.js";
3
+ import { settlePromise } from "./misc.js";
4
+ function delay(options) {
5
+ const { signal, time } = getPromiseOptions(options);
6
+ if (signal?.aborted ?? false) return Promise.reject(signal.reason);
7
+ function abort() {
8
+ cancelAnimationFrame(frame);
9
+ rejector(signal.reason);
10
+ }
11
+ function run(now) {
12
+ start ??= now;
13
+ if (now - start >= time - 5) settlePromise(abort, resolver, void 0, signal);
14
+ else frame = requestAnimationFrame(run);
15
+ }
16
+ signal?.addEventListener("abort", abort, PROMISE_ABORT_OPTIONS);
17
+ let frame;
18
+ let rejector;
19
+ let resolver;
20
+ let start;
21
+ return new Promise((resolve, reject) => {
22
+ rejector = reject;
23
+ resolver = resolve;
24
+ if (time === 0) settlePromise(abort, resolve, void 0, signal);
25
+ else frame = requestAnimationFrame(run);
26
+ });
27
+ }
28
+ export { delay };
@@ -0,0 +1,51 @@
1
+ import { PROMISE_STRATEGY_ALL, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED } from "./models.js";
2
+ function getNumberOrDefault(value) {
3
+ return typeof value === "number" && value > 0 ? value : 0;
4
+ }
5
+ function getPromiseOptions(input) {
6
+ if (typeof input === "number") return { time: getNumberOrDefault(input) };
7
+ if (input instanceof AbortSignal) return {
8
+ signal: input,
9
+ time: 0
10
+ };
11
+ const options = typeof input === "object" && input !== null ? input : {};
12
+ return {
13
+ signal: options.signal instanceof AbortSignal ? options.signal : void 0,
14
+ time: getNumberOrDefault(options.time)
15
+ };
16
+ }
17
+ function getPromisesOptions(input) {
18
+ if (typeof input === "string") return { strategy: getStrategyOrDefault(input) };
19
+ if (input instanceof AbortSignal) return {
20
+ signal: input,
21
+ strategy: PROMISE_STRATEGY_DEFAULT
22
+ };
23
+ const options = typeof input === "object" && input !== null ? input : {};
24
+ return {
25
+ signal: options.signal instanceof AbortSignal ? options.signal : void 0,
26
+ strategy: getStrategyOrDefault(options.strategy)
27
+ };
28
+ }
29
+ function getStrategyOrDefault(value) {
30
+ return PROMISE_STRATEGY_ALL.has(value) ? value : PROMISE_STRATEGY_DEFAULT;
31
+ }
32
+ /**
33
+ * Is the value a fulfilled promise result?
34
+ * @param value Value to check
35
+ * @returns `true` if the value is a fulfilled promise result, `false` otherwise
36
+ */
37
+ function isFulfilled(value) {
38
+ return isType(value, PROMISE_TYPE_FULFILLED);
39
+ }
40
+ /**
41
+ * Is the value a rejected promise result?
42
+ * @param value Value to check
43
+ * @returns `true` if the value is a rejected promise result, `false` otherwise
44
+ */
45
+ function isRejected(value) {
46
+ return isType(value, PROMISE_TYPE_REJECTED);
47
+ }
48
+ function isType(value, type) {
49
+ return typeof value === "object" && value !== null && value.status === type;
50
+ }
51
+ export { getPromiseOptions, getPromisesOptions, getStrategyOrDefault, isFulfilled, isRejected };
@@ -0,0 +1,73 @@
1
+ import { CancelablePromise, PROMISE_ABORT_OPTIONS, PROMISE_EVENT_NAME, PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_MESSAGE_EXPECTATION_PROMISES, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED, PromiseTimeoutError } from "./models.js";
2
+ import { getPromiseOptions, getPromisesOptions, isFulfilled, isRejected } from "./helpers.js";
3
+ import { toPromise } from "../result/misc.js";
4
+ import { cancelable, handleResult, settlePromise, toResult } from "./misc.js";
5
+ import { getTimedPromise, timed } from "./timed.js";
6
+ import { delay } from "./delay.js";
7
+ async function attemptPromise(value, options) {
8
+ const isFunction = typeof value === "function";
9
+ if (!isFunction && !(value instanceof Promise)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_ATTEMPT));
10
+ const { signal, time } = getPromiseOptions(options);
11
+ if (signal?.aborted ?? false) return Promise.reject(signal.reason);
12
+ function abort() {
13
+ rejector(signal.reason);
14
+ }
15
+ async function handler(resolve, reject) {
16
+ try {
17
+ let result = isFunction ? value() : await value;
18
+ if (result instanceof Promise) result = await result;
19
+ settlePromise(abort, resolve, result, signal);
20
+ } catch (error) {
21
+ settlePromise(abort, reject, error, signal);
22
+ }
23
+ }
24
+ let rejector;
25
+ signal?.addEventListener(PROMISE_EVENT_NAME, abort, PROMISE_ABORT_OPTIONS);
26
+ const promise = new Promise((resolve, reject) => {
27
+ rejector = reject;
28
+ handler(resolve, reject);
29
+ });
30
+ return time > 0 ? getTimedPromise(promise, time, signal) : promise;
31
+ }
32
+ async function promises(items, options) {
33
+ const { signal, strategy } = getPromisesOptions(options);
34
+ if (signal?.aborted ?? false) return Promise.reject(signal.reason);
35
+ if (!Array.isArray(items)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_PROMISES));
36
+ const actual = items.filter((item) => item instanceof Promise);
37
+ const { length } = actual;
38
+ if (length === 0) return actual;
39
+ const complete = strategy === PROMISE_STRATEGY_DEFAULT;
40
+ function abort() {
41
+ handlers.reject(signal.reason);
42
+ }
43
+ signal?.addEventListener("abort", abort, PROMISE_ABORT_OPTIONS);
44
+ const data = {
45
+ last: length - 1,
46
+ result: []
47
+ };
48
+ let handlers;
49
+ return new Promise((resolve, reject) => {
50
+ handlers = {
51
+ reject,
52
+ resolve
53
+ };
54
+ for (let index = 0; index < length; index += 1) actual[index].then((value) => handleResult(PROMISE_TYPE_FULFILLED, {
55
+ abort,
56
+ complete,
57
+ data,
58
+ handlers,
59
+ index,
60
+ signal,
61
+ value
62
+ })).catch((reason) => handleResult(PROMISE_TYPE_REJECTED, {
63
+ abort,
64
+ complete,
65
+ data,
66
+ handlers,
67
+ index,
68
+ signal,
69
+ value: reason
70
+ }));
71
+ });
72
+ }
73
+ export { CancelablePromise, PromiseTimeoutError, attemptPromise, cancelable, delay, toPromise as fromResult, isFulfilled, isRejected, promises, timed, toResult };
@@ -0,0 +1,36 @@
1
+ import { CancelablePromise, PROMISE_EVENT_NAME, PROMISE_MESSAGE_EXPECTATION_RESULT } from "./models.js";
2
+ import { error, ok } from "../result/misc.js";
3
+ /**
4
+ * Create a cancelable promise
5
+ * @param executor Executor function for the promise
6
+ * @returns Cancelable promise
7
+ */
8
+ function cancelable(executor) {
9
+ return new CancelablePromise(executor);
10
+ }
11
+ function handleResult(status, parameters) {
12
+ const { abort, complete, data, handlers, index, signal, value } = parameters;
13
+ if (signal?.aborted ?? false) return;
14
+ if (!complete && status === "rejected") {
15
+ settlePromise(abort, handlers.reject, value, signal);
16
+ return;
17
+ }
18
+ data.result[index] = !complete ? value : status === "fulfilled" ? {
19
+ status,
20
+ value
21
+ } : {
22
+ status,
23
+ reason: value
24
+ };
25
+ if (index === data.last) settlePromise(abort, handlers.resolve, data.result, signal);
26
+ }
27
+ function settlePromise(aborter, settler, value, signal) {
28
+ signal?.removeEventListener(PROMISE_EVENT_NAME, aborter);
29
+ settler(value);
30
+ }
31
+ async function toResult(value) {
32
+ const actual = typeof value === "function" ? value() : value;
33
+ if (!(actual instanceof Promise)) return Promise.reject(new TypeError(PROMISE_MESSAGE_EXPECTATION_RESULT));
34
+ return actual.then((result) => ok(result)).catch((reason) => error(reason));
35
+ }
36
+ export { cancelable, handleResult, settlePromise, toResult };