@stacksjs/utils 0.58.72 → 0.59.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/dist/base.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { toString } from '@stacksjs/strings';
2
+ export declare function loop(times: number, callback: any): Promise<void>;
@@ -0,0 +1 @@
1
+ export declare function cleanProject(): Promise<void>;
@@ -0,0 +1 @@
1
+ export { defineApp, defineCache, defineCli, defineCdn, defineCronJob, defineJob, defineDependencies, defineDatabase, defineDns, defineEmailConfig, defineGit, defineHashing, defineLibrary, defineNotification, defineSms, defineEmail, defineChat, definePayment, defineQueue, defineSearchEngine, defineServices, defineStorage, defineUi, } from '@stacksjs/config';
@@ -0,0 +1,3 @@
1
+ export { add, allocate, compare, convert, equal, greaterThan, greaterThanOrEqual, hasSubUnits, isZero, lessThan, lessThanOrEqual, maximum, minimum, multiply, normalizeScale, dinero, dinero as money, subtract, toSnapshot, toUnits, toDecimal, trimScale, haveSameCurrency, haveSameAmount, dinero as currency, } from 'dinero.js';
2
+ export { USD } from '@dinero.js/currencies';
3
+ export type { Dinero, Currency } from 'dinero.js';
@@ -0,0 +1 @@
1
+ export { debounce } from 'perfect-debounce';
@@ -0,0 +1 @@
1
+ export declare function isDeepEqual(value1: any, value2: any): boolean;
@@ -0,0 +1 @@
1
+ export { getExportsSize } from 'export-size';
package/dist/find.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ interface FindStacksProjectsOptions {
2
+ quiet?: boolean;
3
+ }
4
+ export declare function findStacksProjects(dir?: string, options?: FindStacksProjectsOptions): Promise<string[]>;
5
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { Fn, Nullable } from '@stacksjs/types';
2
+ /**
3
+ * Call every function in an array
4
+ */
5
+ export declare function batchInvoke(functions: Nullable<Fn>[]): void;
6
+ /**
7
+ * Pass the value through the callback, and return the value
8
+ *
9
+ * @example
10
+ * ```
11
+ * function createUser(name: string): User {
12
+ * return tap(new User, user => {
13
+ * user.name = name
14
+ * })
15
+ * }
16
+ * ```
17
+ */
18
+ export declare function tap<T>(value: T, callback: (value: T) => void): T;
package/dist/git.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function isGitClean(): boolean;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Type guard to filter out null-ish values
3
+ *
4
+ * @category Guards
5
+ * @example array.filter(notNullish)
6
+ */
7
+ export declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
8
+ /**
9
+ * Type guard to filter out null values
10
+ *
11
+ * @category Guards
12
+ * @example array.filter(noNull)
13
+ */
14
+ export declare function noNull<T>(v: T | null): v is Exclude<T, null>;
15
+ /**
16
+ * Type guard to filter out null-ish values
17
+ *
18
+ * @category Guards
19
+ * @example array.filter(notUndefined)
20
+ */
21
+ export declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
22
+ /**
23
+ * Type guard to filter out falsy values
24
+ *
25
+ * @category Guards
26
+ * @example array.filter(isTruthy)
27
+ */
28
+ export declare function isTruthy<T>(v: T): v is NonNullable<T>;
package/dist/hash.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function originRequestFunctionHash(): string | undefined;
2
+ export declare const websiteSourceHash: string;
@@ -0,0 +1,52 @@
1
+ /// <reference types="bun-types" />
2
+ /// <reference types="node" />
3
+ import type { AddressInfo } from 'node:net';
4
+ import type { Result } from '@stacksjs/error-handling';
5
+ import type { CliOptions, Manifest, SyncSubprocess } from '@stacksjs/types';
6
+ import type { NpmScript } from '@stacksjs/enums';
7
+ export declare function packageManager(): Promise<string>;
8
+ export declare function initProject(): Promise<Result<SyncSubprocess, Error>>;
9
+ export declare function ensureProjectIsInitialized(): Promise<boolean>;
10
+ export declare function installIfVersionMismatch(): Promise<void>;
11
+ export declare function frameworkVersion(): Promise<string>;
12
+ export declare function isAppKeySet(): Promise<boolean>;
13
+ /**
14
+ * Determines the utilized reset preset.
15
+ *
16
+ * @url https://www.npmjs.com/package/@unocss/reset
17
+ * @param preset
18
+ */
19
+ export declare function determineResetPreset(preset?: string): string[];
20
+ /**
21
+ * Determines whether the specified value is a package manifest.
22
+ */
23
+ export declare function isManifest(obj: any): obj is Manifest;
24
+ /**
25
+ * Determines whether the specified value is a string, null, or undefined.
26
+ */
27
+ export declare function isOptionalString(value: any): value is string | undefined;
28
+ export declare function setEnvValue(key: string, value: string): Promise<void>;
29
+ /**
30
+ * Runs the specified NPM script in the package.json file.
31
+ */
32
+ export declare function runNpmScript(script: NpmScript, options?: CliOptions): Promise<Result<SyncSubprocess, Error>>;
33
+ /**
34
+ * Determines whether the specified NPM script exists in the given manifest.
35
+ */
36
+ export declare function hasScript(manifest: Manifest, script: NpmScript): boolean;
37
+ export declare function parseYaml(content: any): any;
38
+ /**
39
+ * Determines the level of debugging.
40
+ *
41
+ * The debug level is determined by the following:
42
+ * 1. The --verbose flag
43
+ * 2. The debug property in the app configuration
44
+ *
45
+ * Currently, we don't support a custom debug level,
46
+ * though, we would like to in the future.
47
+ *
48
+ * @param options
49
+ */
50
+ export declare function determineDebugLevel(options?: CliOptions): boolean;
51
+ export declare function isIpv6(address: AddressInfo): boolean;
52
+ export { dump as dumpYaml, load as loadYaml } from 'js-yaml';
@@ -0,0 +1,23 @@
1
+ export * from './base';
2
+ export * from './clean';
3
+ export * from './config';
4
+ export * from './currency';
5
+ export * from './debounce';
6
+ export * from './equal';
7
+ export * from './export-size';
8
+ export * from './find';
9
+ export * from './function';
10
+ export * from './git';
11
+ export * from './guards';
12
+ export * from './hash';
13
+ export * from './helpers';
14
+ export * from './macroable';
15
+ export * from './math';
16
+ export * from './p';
17
+ export * from './promise';
18
+ export * from './regex';
19
+ export * from './retry';
20
+ export * from './sleep';
21
+ export * from './throttle';
22
+ export * from './vendors';
23
+ export * from './versions';
package/dist/index.js CHANGED
@@ -6,24 +6,18 @@ async function loop(times, callback) {
6
6
  }
7
7
  // src/clean.ts
8
8
  import {path as p} from "@stacksjs/path";
9
-
10
- // src/delete.ts
11
- import {rimraf} from "rimraf";
12
-
13
- // src/clean.ts
9
+ var {$ } = globalThis.Bun;
14
10
  async function cleanProject() {
15
- return await rimraf([
16
- p.projectPath("bun.lockb"),
17
- p.projectPath("yarn.lock"),
18
- p.projectPath("node_modules/"),
19
- p.frameworkPath("dist"),
20
- p.frameworkPath("node_modules"),
21
- p.frameworkPath("**/dist"),
22
- p.frameworkPath("**/node_modules"),
23
- p.frameworkCloudPath("cdk.out/"),
24
- p.frameworkCloudPath("cdk.context.json"),
25
- p.frameworkCloudPath("dist.zip")
26
- ]);
11
+ await $`rm -rf ${p.projectPath("bun.lockb")}`;
12
+ await $`rm -rf ${p.projectPath("yarn.lock")}`;
13
+ await $`rm -rf ${p.projectPath("node_modules/")}`;
14
+ await $`rm -rf ${p.frameworkPath("dist")}`;
15
+ await $`rm -rf ${p.frameworkPath("node_modules")}`;
16
+ await $`rm -rf ${p.frameworkPath("**/dist")}`;
17
+ await $`rm -rf ${p.frameworkPath("**/node_modules")}`;
18
+ await $`rm -rf ${p.frameworkCloudPath("cdk.out/")}`;
19
+ await $`rm -rf ${p.frameworkCloudPath("cdk.context.json")}`;
20
+ await $`rm -rf ${p.frameworkCloudPath("dist.zip")}`;
27
21
  }
28
22
  // src/config.ts
29
23
  import {
@@ -108,6 +102,74 @@ function isDeepEqual(value1, value2) {
108
102
  }
109
103
  // src/export-size.ts
110
104
  import {getExportsSize} from "export-size";
105
+ // src/find.ts
106
+ import os from "os";
107
+ import fs from "fs/promises";
108
+ import path2 from "path";
109
+ import {italic} from "@stacksjs/cli";
110
+ import {log as log2} from "@stacksjs/logging";
111
+ async function findStacksProjects(dir, options) {
112
+ dir = dir || os.homedir();
113
+ if (!options?.quiet) {
114
+ log2.info(`Searching for Stacks projects in: ${italic(dir)}`);
115
+ log2.info(`This may take a few moments...`);
116
+ console.log("");
117
+ console.log(italic(" Please note, while Stacks is searching for projects on your machine,"));
118
+ console.log(italic(" you may be asked for permissions to scan certain directories."));
119
+ console.log("");
120
+ log2.debug(`Excluding directories: ${excludePatterns.join(", ")}`);
121
+ }
122
+ const foundProjects = await searchDirectory(dir);
123
+ if (!foundProjects)
124
+ throw new Error("No Stacks projects found");
125
+ return foundProjects;
126
+ }
127
+ async function searchDirectory(directory) {
128
+ const foundProjects = [];
129
+ const isExcluded = excludePatterns.some((pattern) => typeof pattern === "string" ? directory.includes(pattern) : pattern.test(directory));
130
+ if (isExcluded)
131
+ return;
132
+ let items;
133
+ try {
134
+ items = await fs.readdir(directory, { withFileTypes: true });
135
+ } catch (error) {
136
+ console.error(`Error reading directory ${directory}:`, error);
137
+ return;
138
+ }
139
+ let buddyFileFound = false;
140
+ let storageDirFound = false;
141
+ for (const item of items) {
142
+ if (item.isFile() && item.name === targetFileName) {
143
+ buddyFileFound = true;
144
+ } else if (item.isDirectory()) {
145
+ const fullPath = path2.join(directory, item.name);
146
+ if (item.name === "storage") {
147
+ try {
148
+ const storagePath = path2.join(fullPath, "framework/core/buddy");
149
+ await fs.access(storagePath);
150
+ storageDirFound = true;
151
+ } catch (error) {
152
+ }
153
+ }
154
+ await searchDirectory(fullPath);
155
+ }
156
+ }
157
+ if (buddyFileFound && storageDirFound)
158
+ foundProjects.push(directory);
159
+ return foundProjects;
160
+ }
161
+ var targetFileName = "buddy";
162
+ var excludePatterns = [
163
+ "node_modules",
164
+ "dist",
165
+ "vendor",
166
+ `${os.homedir()}/Documents`,
167
+ `${os.homedir()}/Pictures`,
168
+ `${os.homedir()}/Library`,
169
+ `${os.homedir()}/.Trash`,
170
+ /.*out.*|.*\.out.*|out-.*/,
171
+ /.*\/\..*/
172
+ ];
111
173
  // src/function.ts
112
174
  function batchInvoke(functions) {
113
175
  functions.forEach((fn) => fn && fn());
@@ -161,7 +223,7 @@ var websiteSrc = [
161
223
  ];
162
224
  var websiteSourceHash = config2.app.docMode === true ? hashPaths(docsSrc) : hashPaths(websiteSrc);
163
225
  // src/helpers.ts
164
- import {log as log2, runCommand} from "@stacksjs/cli";
226
+ import {log as log3, runCommand} from "@stacksjs/cli";
165
227
  import {err, handleError, ok} from "@stacksjs/error-handling";
166
228
  import {frameworkPath, projectPath} from "@stacksjs/path";
167
229
  import * as storage2 from "@stacksjs/storage";
@@ -174,13 +236,13 @@ async function packageManager() {
174
236
  }
175
237
  async function initProject() {
176
238
  if (app.env !== "production")
177
- log2.info("Project not yet initialized, generating application key...");
239
+ log3.info("Project not yet initialized, generating application key...");
178
240
  else
179
241
  handleError("Please run `buddy key:generate` to generate an application key");
180
242
  const result = await runAction(Action.KeyGenerate, { cwd: projectPath() });
181
243
  if (result.isErr())
182
244
  return err(handleError(result.error));
183
- log2.info("Application key generated.");
245
+ log3.info("Application key generated.");
184
246
  return ok(result.value);
185
247
  }
186
248
  async function ensureProjectIsInitialized() {
@@ -408,89 +470,8 @@ function createControlledPromise() {
408
470
  promise.reject = reject;
409
471
  return promise;
410
472
  }
411
- // /home/runner/work/stacks/stacks/node_modules/magic-regexp/dist/shared/magic-regexp.b7c910ac.mjs
412
- var NO_WRAP_RE = /^(\(.*\)|\\?.)$/;
413
- var wrap = (s) => {
414
- const v = s.toString();
415
- return NO_WRAP_RE.test(v) ? v : `(?:${v})`;
416
- };
417
- var GROUPED_AS_REPLACE_RE = /^(?:\(\?:(.+)\)|(\(?.+\)?))$/;
418
- var GROUPED_REPLACE_RE = /^(?:\(\?:(.+)\)([?+*]|{[\d,]+})?|(.+))$/;
419
- var createInput = (s) => {
420
- const groupedAsFn = (key) => createInput(`(?<${key}>${`${s}`.replace(GROUPED_AS_REPLACE_RE, "$1$2")})`);
421
- return {
422
- toString: () => s.toString(),
423
- and: Object.assign((...inputs) => createInput(`${s}${exactly(...inputs)}`), {
424
- referenceTo: (groupName) => createInput(`${s}\\k<${groupName}>`)
425
- }),
426
- or: (...inputs) => createInput(`(?:${s}|${exactly(...inputs)})`),
427
- after: (...input) => createInput(`(?<=${exactly(...input)})${s}`),
428
- before: (...input) => createInput(`${s}(?=${exactly(...input)})`),
429
- notAfter: (...input) => createInput(`(?<!${exactly(...input)})${s}`),
430
- notBefore: (...input) => createInput(`${s}(?!${exactly(...input)})`),
431
- times: Object.assign((number) => createInput(`${wrap(s)}{${number}}`), {
432
- any: () => createInput(`${wrap(s)}*`),
433
- atLeast: (min) => createInput(`${wrap(s)}{${min},}`),
434
- atMost: (max) => createInput(`${wrap(s)}{0,${max}}`),
435
- between: (min, max) => createInput(`${wrap(s)}{${min},${max}}`)
436
- }),
437
- optionally: () => createInput(`${wrap(s)}?`),
438
- as: groupedAsFn,
439
- groupedAs: groupedAsFn,
440
- grouped: () => createInput(`${s}`.replace(GROUPED_REPLACE_RE, "($1$3)$2")),
441
- at: {
442
- lineStart: () => createInput(`^${s}`),
443
- lineEnd: () => createInput(`${s}\$`)
444
- }
445
- };
446
- };
447
- var ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
448
- var charIn = (chars) => createInput(`[${chars.replace(/[-\\^\]]/g, "\\$&")}]`);
449
- var charNotIn = (chars) => createInput(`[^${chars.replace(/[-\\^\]]/g, "\\$&")}]`);
450
- var anyOf = (...inputs) => createInput(`(?:${inputs.map((a) => exactly(a)).join("|")})`);
451
- var char = createInput(".");
452
- var word = createInput("\\b\\w+\\b");
453
- var wordChar = createInput("\\w");
454
- var wordBoundary = createInput("\\b");
455
- var digit = createInput("\\d");
456
- var whitespace = createInput("\\s");
457
- var letter = Object.assign(createInput("[a-zA-Z]"), {
458
- lowercase: createInput("[a-z]"),
459
- uppercase: createInput("[A-Z]")
460
- });
461
- var tab = createInput("\\t");
462
- var linefeed = createInput("\\n");
463
- var carriageReturn = createInput("\\r");
464
- var not = {
465
- word: createInput("\\W+"),
466
- wordChar: createInput("\\W"),
467
- wordBoundary: createInput("\\B"),
468
- digit: createInput("\\D"),
469
- whitespace: createInput("\\S"),
470
- letter: Object.assign(createInput("[^a-zA-Z]"), {
471
- lowercase: createInput("[^a-z]"),
472
- uppercase: createInput("[^A-Z]")
473
- }),
474
- tab: createInput("[^\\t]"),
475
- linefeed: createInput("[^\\n]"),
476
- carriageReturn: createInput("[^\\r]")
477
- };
478
- var maybe = (...inputs) => createInput(`${wrap(exactly(...inputs))}?`);
479
- var exactly = (...inputs) => createInput(inputs.map((input) => typeof input === "string" ? input.replace(ESCAPE_REPLACE_RE, "\\$&") : input).join(""));
480
- var oneOrMore = (...inputs) => createInput(`${wrap(exactly(...inputs))}+`);
481
- var withIndices = "d";
482
- var caseInsensitive = "i";
483
- var global = "g";
484
- var multiline = "m";
485
- var dotAll = "s";
486
- var unicode = "u";
487
- var sticky = "y";
488
-
489
- // /home/runner/work/stacks/stacks/node_modules/magic-regexp/dist/index.mjs
490
- var createRegExp = (...inputs) => {
491
- const flags = inputs.length > 1 && (Array.isArray(inputs[inputs.length - 1]) || inputs[inputs.length - 1] instanceof Set) ? inputs.pop() : undefined;
492
- return new RegExp(exactly(...inputs).toString(), [...flags || ""].join(""));
493
- };
473
+ // src/regex.ts
474
+ import {createRegExp, caseInsensitive, anyOf, carriageReturn, char, charIn, charNotIn, digit, dotAll, exactly, global, letter, linefeed, maybe, multiline, not, oneOrMore, sticky, tab, unicode, whitespace, withIndices, word, wordBoundary, wordChar} from "magic-regexp";
494
475
  // src/retry.ts
495
476
  function retry(fn, options) {
496
477
  const { retries = 3, initialDelay = 1000, backoffFactor = 2, jitter = true } = options;
@@ -823,7 +804,7 @@ createHead,
823
804
  renderHeadToString
824
805
  } from "@vueuse/head";
825
806
 
826
- // /home/runner/work/stacks/stacks/node_modules/pretty-bytes/index.js
807
+ // ../../../../node_modules/pretty-bytes/index.js
827
808
  var BYTE_UNITS = [
828
809
  "B",
829
810
  "kB",
@@ -918,7 +899,7 @@ function prettyBytes(number, options) {
918
899
  return prefix + numberString + separator + unit;
919
900
  }
920
901
  // package.json
921
- var version = "0.58.72";
902
+ var version = "0.59.1";
922
903
  export {
923
904
  wordChar,
924
905
  wordBoundary,
@@ -1135,7 +1116,6 @@ export {
1135
1116
  setSSRHandler,
1136
1117
  setEnvValue,
1137
1118
  runNpmScript,
1138
- rimraf,
1139
1119
  retry,
1140
1120
  resolveUnref,
1141
1121
  resolveRef,
@@ -1212,6 +1192,7 @@ export {
1212
1192
  getExportsSize,
1213
1193
  frameworkVersion,
1214
1194
  formatTimeAgo,
1195
+ findStacksProjects,
1215
1196
  extendRef,
1216
1197
  executeTransition,
1217
1198
  exactly,
@@ -0,0 +1 @@
1
+ export { Macroable } from 'macroable';
package/dist/math.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare const clamp: (n: number, min: number, max: number) => number;
2
+ export declare function rand(min: number, max: number): number;
3
+ export { and, createGenericProjection, createProjection, logicNot, logicOr, or, useAbs, useAverage, useCeil, useClamp, useFloor, useMath, useMax, useMin, usePrecision, useProjection, useRound, useSum, useTrunc, } from '@vueuse/math';
package/dist/p.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ interface POptions {
2
+ /**
3
+ * How many promises are resolved at the same time.
4
+ */
5
+ concurrency?: number | undefined;
6
+ }
7
+ declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
8
+ items: Iterable<T>;
9
+ options?: POptions | undefined;
10
+ private promises;
11
+ get promise(): Promise<Awaited<T>[]>;
12
+ constructor(items?: Iterable<T>, options?: POptions | undefined);
13
+ add(...args: (T | Promise<T>)[]): void;
14
+ map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
15
+ filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
16
+ forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
17
+ reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
18
+ clear(): void;
19
+ then(fn?: () => PromiseLike<any>): Promise<any>;
20
+ catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
21
+ finally(fn?: () => void): Promise<Awaited<T>[]>;
22
+ }
23
+ /**
24
+ * Utility for managing multiple promises.
25
+ *
26
+ * @see https://github.com/antfu/utils/tree/main/docs/p.md
27
+ * @category Promise
28
+ * @example
29
+ * ```
30
+ * import { p } from '@stacksjs/utils'
31
+ *
32
+ * const items = [1, 2, 3, 4, 5]
33
+ *
34
+ * await p(items)
35
+ * .map(async i => await multiply(i, 3))
36
+ * .filter(async i => await isEven(i))
37
+ * // [6, 12]
38
+ * ```
39
+ */
40
+ export declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
41
+ export {};
@@ -0,0 +1,61 @@
1
+ export interface SingletonPromiseReturn<T> {
2
+ (): Promise<T>;
3
+ /**
4
+ * Reset current staled promise.
5
+ * Await it to have proper shutdown.
6
+ */
7
+ reset: () => Promise<void>;
8
+ }
9
+ /**
10
+ * Promise with `resolve` and `reject` methods of itself
11
+ */
12
+ export interface ControlledPromise<T = void> extends Promise<T> {
13
+ resolve: (value: T | PromiseLike<T>) => void;
14
+ reject: (reason?: any) => void;
15
+ }
16
+ /**
17
+ * Create singleton promise function.
18
+ *
19
+ * @category Promise
20
+ */
21
+ export declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
22
+ /**
23
+ * Create a promise lock.
24
+ *
25
+ * @category Promise
26
+ * @example
27
+ * ```
28
+ * const lock = createPromiseLock()
29
+ *
30
+ * lock.run(async () => {
31
+ * await doSomething()
32
+ * })
33
+ *
34
+ * // in anther context:
35
+ * await lock.wait() // it will wait all tasking finished
36
+ * ```
37
+ */
38
+ export declare function createPromiseLock(): {
39
+ run<T = void>(fn: () => Promise<T>): Promise<T>;
40
+ wait(): Promise<void>;
41
+ isWaiting(): boolean;
42
+ clear(): void;
43
+ };
44
+ /**
45
+ * Return a Promise with `resolve` and `reject` methods
46
+ *
47
+ * @category Promise
48
+ * @example
49
+ * ```
50
+ * const promise = createControlledPromise()
51
+ *
52
+ * await promise
53
+ *
54
+ * // in anther context:
55
+ * promise.resolve(data)
56
+ * ```
57
+ */
58
+ export declare function createControlledPromise<T>(): ControlledPromise<T>;
59
+ /**
60
+ * Create a promise that will be resolved after `ms` milliseconds.
61
+ */
@@ -0,0 +1,2 @@
1
+ export type { Flag, MagicRegExp, MagicRegExpMatchArray, Input, MapToStringCapturedBy, StringCapturedBy } from 'magic-regexp';
2
+ export { createRegExp, caseInsensitive, anyOf, carriageReturn, char, charIn, charNotIn, digit, dotAll, exactly, global, letter, linefeed, maybe, multiline, not, oneOrMore, sticky, tab, unicode, whitespace, withIndices, word, wordBoundary, wordChar } from 'magic-regexp';
@@ -0,0 +1,2 @@
1
+ export declare function retry(fn: Function, options: any): Promise<any>;
2
+ export declare function calculateDelay(attemptCount: number, initialDelay: number, backoffFactor: number, jitter?: boolean): number;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Pauses execution for a specified number of milliseconds.
3
+ * @param ms The number of milliseconds to pause execution.
4
+ * @returns A promise that resolves after the specified delay.
5
+ */
6
+ export declare function sleep(ms: number): Promise<void>;
7
+ /**
8
+ * Pauses execution for a specified number of milliseconds.
9
+ * @param ms The number of milliseconds to pause execution.
10
+ * @returns A promise that resolves after the specified delay.
11
+ */
12
+ export declare function wait(ms: number): Promise<void>;
13
+ /**
14
+ * Pauses execution for a specified number of milliseconds.
15
+ * @param ms The number of milliseconds to pause execution.
16
+ * @returns A promise that resolves after the specified delay.
17
+ */
18
+ export declare function delay(ms: number): Promise<void>;
19
+ /**
20
+ * Pauses execution until a specified condition is met.
21
+ * @param condition The condition to wait for.
22
+ * @param interval The interval at which to check the condition, in milliseconds. Defaults to 1000.
23
+ * @returns A promise that resolves when the condition is met.
24
+ */
25
+ export declare function waitUntil(condition: () => boolean, interval?: number): Promise<void>;
26
+ /**
27
+ * Pauses execution while a specified condition is met.
28
+ * @param condition The condition to wait while.
29
+ * @param interval The interval at which to check the condition, in milliseconds. Defaults to 1000.
30
+ * @returns A promise that resolves when the condition is no longer met.
31
+ */
32
+ export declare function waitWhile(condition: () => boolean, interval?: number): Promise<void>;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Throttle a function.
3
+ *
4
+ * @param {Function} fn - The function to throttle.
5
+ * @param {number} [wait] - The time to wait between function calls.
6
+ * @returns {Function} - A new function that throttles the calls to the original function.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * // logs window dimensions at most every 250ms
11
+ * window.addEventListener(
12
+ * "resize",
13
+ * throttle(function (evt) {
14
+ * console.log(window.innerWidth)
15
+ * console.log(window.innerHeight)
16
+ * }, 250)
17
+ * )
18
+ * ```
19
+ */
20
+ export declare function throttle(fn: Function, wait?: number): (this: unknown, ...args: any[]) => void;
@@ -0,0 +1,4 @@
1
+ export { asyncComputed, breakpointsAntDesign, breakpointsBootstrapV5, breakpointsMasterCss, breakpointsQuasar, breakpointsSematic, breakpointsTailwind, breakpointsVuetify, cloneFnJSON, computedAsync, computedInject, createFetch, createReusableTemplate, createTemplatePromise, createUnrefFn, customStorageEventName, defaultDocument, defaultLocation, defaultNavigator, defaultWindow, executeTransition, formatTimeAgo, getSSRHandler, mapGamepadToXbox360Controller, onClickOutside, onKeyDown, onKeyPressed, onKeyStroke, onKeyUp, onLongPress, onStartTyping, setSSRHandler, templateRef, unrefElement, useActiveElement, useAnimate, useAsyncQueue, useAsyncState, useBase64, useBattery, useBluetooth, useBreakpoints, useBroadcastChannel, useBrowserLocation, useCached, useClipboard, useCloned, useColorMode, useConfirmDialog, useCssVar, useCurrentElement, useCycleList, useDark, useDebouncedRefHistory, useDeviceMotion, useDeviceOrientation, useDevicePixelRatio, useDevicesList, useDisplayMedia, useDocumentVisibility, useDraggable, useDropZone, useElementBounding, useElementByPoint, useElementHover, useElementSize, useElementVisibility, useEventBus, useEventListener, useEventSource, useEyeDropper, useFavicon, useFetch, useFileDialog, useFileSystemAccess, useFocus, useFocusWithin, useFps, useFullscreen, useGamepad, useGeolocation, useIdle, useImage, useInfiniteScroll, useIntersectionObserver, useKeyModifier, useLocalStorage, useMagicKeys, useManualRefHistory, useMediaControls, useMediaQuery, useMemoize, useMemory, useMounted, useMouse, useMouseInElement, useMousePressed, useMutationObserver, useNavigatorLanguage, useNetwork, useObjectUrl, useOffsetPagination, useOnline, usePageLeave, useParallax, useParentElement, usePerformanceObserver, usePermission, usePointer, usePointerLock, usePointerSwipe, usePreferredColorScheme, usePreferredContrast, usePreferredDark, usePreferredLanguages, usePreferredReducedMotion, usePrevious, useRafFn, useRefHistory, useResizeObserver, useScreenOrientation, useScreenSafeArea, useScriptTag, useScroll, useScrollLock, useSessionStorage, useShare, useSorted, useSpeechRecognition, useSpeechSynthesis, useStepper, useStorage, useStorageAsync, useStyleTag, useSupported, useSwipe, useTemplateRefsList, useTextDirection, useTextSelection, useTextareaAutosize, useThrottledRefHistory, useTimeAgo, useTimeoutPoll, useTimestamp, useTitle, useTransition, useToggle, useUrlSearchParams, useUserMedia, useVModel, useVModels, useVibrate, useVirtualList, useWakeLock, useWebNotification, useWebSocket, useWebWorker, useWebWorkerFn, useWindowFocus, useWindowScroll, useWindowSize, useDateFormat, useNow, watchArray, watchAtMost, watchDebounced, watchDeep, watchIgnorable, watchImmediate, watchOnce, watchPausable, watchThrottled, watchTriggerable, watchWithFilter, whenever, syncRef, syncRefs, throttledRef, throttledWatch, toReactive, tryOnBeforeMount, tryOnBeforeUnmount, tryOnMounted, tryOnScopeDispose, tryOnUnmounted, until, isDefined, ignorableWatch, extendRef, eagerComputed, debouncedRef, debouncedWatch, createReactiveFn, createSharedComposable, createInjectionState, createGlobalState, createEventHook, controlledRef, controlledComputed, computedEager, computedWithControl, autoResetRef, injectLocal, makeDestructurable, pausableWatch, provideLocal, reactify, reactifyObject, reactiveComputed, reactiveOmit, reactivePick, refAutoReset, refDebounced, refDefault, refThrottled, refWithControl, resolveRef, resolveUnref, useArrayDifference, useArrayEvery, useArrayFilter, useArrayFind, useArrayFindIndex, useArrayIncludes, useArrayMap, useArrayReduce, useArraySome, useArrayUnique, useClipboardItems, useCounter, useDebounce, useDebounceFn, useInterval, useIntervalFn, useLastChanged, useThrottle, useThrottleFn, useTimeout, useTimeoutFn, useToNumber, useToString, } from '@vueuse/core';
2
+ export type { HeadObject, HeadObjectPlain, } from '@vueuse/head';
3
+ export { Head, HeadVuePlugin, createHead, renderHeadToString, } from '@vueuse/head';
4
+ export { default as readableSize } from 'pretty-bytes';
@@ -0,0 +1,2 @@
1
+ import { version } from '../package.json';
2
+ export { version };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/utils",
3
3
  "type": "module",
4
- "version": "0.58.72",
4
+ "version": "0.59.1",
5
5
  "description": "The Stacks helper functions.",
6
6
  "author": "Chris Breuer",
7
7
  "license": "MIT",
@@ -63,14 +63,14 @@
63
63
  "@stacksjs/strings": "latest",
64
64
  "@stacksjs/types": "latest",
65
65
  "@types/js-yaml": "^4.0.9",
66
- "@vueuse/core": "^10.7.2",
66
+ "@vueuse/core": "^10.9.0",
67
67
  "@vueuse/head": "^2.0.0",
68
- "@vueuse/math": "^10.7.2",
69
- "@vueuse/shared": "^10.7.2",
68
+ "@vueuse/math": "^10.9.0",
69
+ "@vueuse/shared": "^10.9.0",
70
+ "bun-plugin-env": "^0.4.1",
71
+ "bun-plugin-yml": "^0.3.0",
70
72
  "export-size": "^0.7.0",
71
- "js-yaml": "^4.1.0",
72
- "rimraf": "^5.0.5",
73
- "yaml": "^2.3.4"
73
+ "yaml": "^2.4.0"
74
74
  },
75
75
  "dependencies": {
76
76
  "@dinero.js/currencies": "2.0.0-alpha.14",
@@ -83,10 +83,12 @@
83
83
  "@stacksjs/storage": "latest",
84
84
  "@stacksjs/strings": "latest",
85
85
  "@stacksjs/types": "latest",
86
- "@vueuse/core": "^10.7.2",
86
+ "@vueuse/core": "^10.9.0",
87
87
  "@vueuse/head": "^2.0.0",
88
- "@vueuse/math": "^10.7.2",
89
- "@vueuse/shared": "^10.7.2",
88
+ "@vueuse/math": "^10.9.0",
89
+ "@vueuse/shared": "^10.9.0",
90
+ "bun-plugin-env": "^0.4.1",
91
+ "bun-plugin-yml": "^0.3.0",
90
92
  "defu": "^6.1.4",
91
93
  "detect-indent": "^7.0.1",
92
94
  "detect-newline": "^4.0.1",
@@ -99,8 +101,7 @@
99
101
  "p-limit": "^5.0.0",
100
102
  "perfect-debounce": "^1.0.0",
101
103
  "pretty-bytes": "^6.1.1",
102
- "rimraf": "^5.0.5",
103
- "yaml": "^2.3.4"
104
+ "yaml": "^2.4.0"
104
105
  },
105
106
  "devDependencies": {
106
107
  "@stacksjs/development": "latest",
package/src/clean.ts CHANGED
@@ -1,17 +1,15 @@
1
1
  import { path as p } from '@stacksjs/path'
2
- import { rimraf } from './delete'
2
+ import { $ } from 'bun'
3
3
 
4
4
  export async function cleanProject() {
5
- return await rimraf([
6
- p.projectPath('bun.lockb'),
7
- p.projectPath('yarn.lock'),
8
- p.projectPath('node_modules/'),
9
- p.frameworkPath('dist'),
10
- p.frameworkPath('node_modules'),
11
- p.frameworkPath('**/dist'),
12
- p.frameworkPath('**/node_modules'),
13
- p.frameworkCloudPath('cdk.out/'),
14
- p.frameworkCloudPath('cdk.context.json'),
15
- p.frameworkCloudPath('dist.zip'),
16
- ])
5
+ await $`rm -rf ${p.projectPath('bun.lockb')}`
6
+ await $`rm -rf ${p.projectPath('yarn.lock')}` // just in case
7
+ await $`rm -rf ${p.projectPath('node_modules/')}`
8
+ await $`rm -rf ${p.frameworkPath('dist')}`
9
+ await $`rm -rf ${p.frameworkPath('node_modules')}`
10
+ await $`rm -rf ${p.frameworkPath('**/dist')}`
11
+ await $`rm -rf ${p.frameworkPath('**/node_modules')}`
12
+ await $`rm -rf ${p.frameworkCloudPath('cdk.out/')}`
13
+ await $`rm -rf ${p.frameworkCloudPath('cdk.context.json')}`
14
+ await $`rm -rf ${p.frameworkCloudPath('dist.zip')}`
17
15
  }
package/src/find.ts ADDED
@@ -0,0 +1,97 @@
1
+ import os from 'node:os'
2
+ import fs from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import type { Dirent } from 'node:fs'
5
+ import { italic } from '@stacksjs/cli'
6
+ import { log } from '@stacksjs/logging'
7
+
8
+ const targetFileName = 'buddy' // The exact name of the target file
9
+
10
+ // Assuming excludePatterns is defined somewhere in your script
11
+ const excludePatterns = [
12
+ 'node_modules',
13
+ 'dist',
14
+ 'vendor',
15
+ `${os.homedir()}/Documents`,
16
+ `${os.homedir()}/Pictures`,
17
+ `${os.homedir()}/Library`,
18
+ `${os.homedir()}/.Trash`,
19
+ /.*out.*|.*\.out.*|out-.*/, // exclude any folder with 'out' in the name
20
+ /.*\/\..*/, // exclude any folder that starts with a dot
21
+ ]
22
+
23
+ interface FindStacksProjectsOptions {
24
+ quiet?: boolean
25
+ }
26
+
27
+ export async function findStacksProjects(dir?: string, options?: FindStacksProjectsOptions): Promise<string[]> {
28
+ dir = dir || os.homedir()
29
+
30
+ if (!options?.quiet) {
31
+ log.info(`Searching for Stacks projects in: ${italic(dir)}`)
32
+ log.info(`This may take a few moments...`)
33
+ // eslint-disable-next-line no-console
34
+ console.log('')
35
+ // eslint-disable-next-line no-console
36
+ console.log(italic(' Please note, while Stacks is searching for projects on your machine,'))
37
+ // eslint-disable-next-line no-console
38
+ console.log(italic(' you may be asked for permissions to scan certain directories.'))
39
+ // eslint-disable-next-line no-console
40
+ console.log('')
41
+ log.debug(`Excluding directories: ${excludePatterns.join(', ')}`)
42
+ }
43
+
44
+ const foundProjects = await searchDirectory(dir)
45
+
46
+ if (!foundProjects)
47
+ throw new Error('No Stacks projects found')
48
+
49
+ return foundProjects
50
+ }
51
+
52
+ async function searchDirectory(directory: string) {
53
+ const foundProjects: string[] = []
54
+
55
+ const isExcluded = excludePatterns.some(pattern => typeof pattern === 'string' ? directory.includes(pattern) : pattern.test(directory))
56
+ if (isExcluded)
57
+ return
58
+
59
+ let items: Dirent[]
60
+ try {
61
+ items = await fs.readdir(directory, { withFileTypes: true })
62
+ }
63
+ catch (error) {
64
+ console.error(`Error reading directory ${directory}:`, error)
65
+ return
66
+ }
67
+
68
+ let buddyFileFound = false
69
+ let storageDirFound = false
70
+
71
+ for (const item of items) {
72
+ if (item.isFile() && item.name === targetFileName) {
73
+ buddyFileFound = true
74
+ }
75
+ else if (item.isDirectory()) {
76
+ // Recursively search in directories
77
+ const fullPath = path.join(directory, item.name)
78
+ if (item.name === 'storage') {
79
+ // Check if the 'storage/framework/core/buddy/' structure exists within this directory
80
+ try {
81
+ const storagePath = path.join(fullPath, 'framework/core/buddy')
82
+ await fs.access(storagePath)
83
+ storageDirFound = true
84
+ }
85
+ catch (error) {
86
+ // The specific directory structure does not exist
87
+ }
88
+ }
89
+ await searchDirectory(fullPath)
90
+ }
91
+ }
92
+
93
+ if (buddyFileFound && storageDirFound)
94
+ foundProjects.push(directory) // Both conditions are met
95
+
96
+ return foundProjects
97
+ }
package/src/index.ts CHANGED
@@ -3,9 +3,9 @@ export * from './clean'
3
3
  export * from './config'
4
4
  export * from './currency'
5
5
  export * from './debounce'
6
- export * from './delete'
7
6
  export * from './equal'
8
7
  export * from './export-size'
8
+ export * from './find'
9
9
  export * from './function'
10
10
  export * from './git'
11
11
  export * from './guards'
package/src/delete.ts DELETED
@@ -1 +0,0 @@
1
- export { rimraf } from 'rimraf'